3v4l.org

run code in 300+ PHP versions simultaneously
<?php abstract class Singleton { /** * @var Singleton[] The reference to *Singleton* instances of any child class. */ private static $instances = array(); /** * Returns the *Singleton* instance of this class. * * @return static The *Singleton* instance. */ public static function getInstance() { if (!isset(self::$instances[static::class])) { self::$instances[static::class] = new static(); } return self::$instances[static::class]; } /** * Protected constructor to prevent creating a new instance of the * *Singleton* via the `new` operator from outside of this class. */ protected function __construct() { } /** * Private clone method to prevent cloning of the instance of the * *Singleton* instance. * * @return void */ private function __clone() { } /** * Private unserialize method to prevent unserializing of the *Singleton* * instance. * * @return void */ private function __wakeup() { } } class SingletonChild extends Singleton { } class AnotherChild extends Singleton { } echo 'Expect: true, true, true, false' . PHP_EOL; var_dump(SingletonChild::getInstance() === SingletonChild::getInstance()); var_dump(AnotherChild::getInstance() === AnotherChild::getInstance()); $a = AnotherChild::getInstance(); var_dump($a === AnotherChild::getInstance()); var_dump($a === SingletonChild::getInstance());

preferences:
34.36 ms | 404 KiB | 5 Q