2

class singleton:

class Singleton
{
    private static $_myself;

    private function __construct(){}

    public static function getInstance()
    {
        if(!isset(self::$_myself))
        {
            $obj = __CLASS__;
            self::$_myself = new $obj;
        }
        return self::$_myself;
    }
}

my class:

 class MyApp extends Singleton
    {
        public function show()
        {
            echo 'show';
        }
    }
    MyApp::getInstance()->show();

but not working, this error: Call to undefined method Singleton::show() somebody can help me?

1
  • This pattern creates lots of tight coupling, which makes your application harder to evolve, test, and re-use. The singleton pattern is fine (one instance used in lots of places), but this very common static function pattern causes a lot of problems. Please use a dependency injection framework. After looking around a bit, PHP-DI looks nice: php-di.org Commented Feb 24, 2014 at 18:08

3 Answers 3

3

Because you're returning a Singleton class (as you can see by your error), but should be returning a MyApp class. You can do this by using the late static binding method get_called_class() introduced in PHP 5.3:

public static function getInstance()
{
    if(!isset(self::$_myself))
    {
        //__CLASS__ = Singleton | get_called_class() = MyApp
        $obj = get_called_class(); 
        self::$_myself = new $obj;
    }
    return self::$_myself;
}
Sign up to request clarification or add additional context in comments.

Comments

2

self returns the actual class instance (Singleton in this case), so there is no method show. But you could use static instead of self (Differences) and change $_myself from private to protected so it is accessible in child classes.

class Singleton
{
    protected static $_myself;

    private function __construct(){}

    public static function getInstance()
    {
        if(!isset(static::$_myself))
        {
            static::$_myself = new static;
        }
        return static::$_myself;
    }
}

Comments

-1

The problem is in

$obj = __CLASS__;
self::$_myself = new $obj;

You create a new instance of the class Singleton, not of the class MyApp, so the method is not available.

Now h2ooooooo was faster with his answer than I edited, see his answer regarding what to put instead of __CLASS__.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.