2

I am reading about Patterns in OOP and came across this code for the singleton pattern:

class Singleton
{
    /**
     * @var Singleton reference to singleton instance
     */
    private static $instance;

    /**
     * gets the instance via lazy initialization (created on first usage)
     *
     * @return self
     */
    public static function getInstance()
    {

        if (null === static::$instance) {
            static::$instance = new static;
        }

        return static::$instance;
    }

    /**
     * is not allowed to call from outside: private!
     *
     */
    private function __construct()
    {

    }

    /**
     * prevent the instance from being cloned
     *
     * @return void
     */
    private function __clone()
    {

    }

    /**
     * prevent from being unserialized
     *
     * @return void
     */
    private function __wakeup()
    {

    }
}

The part in question is static::$instance = new static;. What exactly does new static do or how does this example work. I am familiar with your average new Object but not new static. Any references to php documentation would help greatly.

Robert
  • 10,126
  • 19
  • 78
  • 130

1 Answers1

2

basically that is a extendable class, and whenever you call getInstance() you will get a singleton of the whatever class you call it in (that extends this singleton class). If you only use it in one instance, you could hardcode the classname, or use new self if you had hardcoded this in your class.

Also, the singleton is regarded a anti-pattern, see the answer her for more details on this pattern why-is-singleton-considered-an-anti-pattern

Community
  • 1
  • 1
Richard87
  • 1,592
  • 3
  • 16
  • 29