PHP Singlethon implementation
Published on 12.11.2015
Example of quick singlethon implementation in PHP
<?php abstract class Singleton { // protected static $INSTANCE; /** * Protected constructor to prevent creating a new instance of the * @return void */ final private function __construct() { } /** * Private clone method to prevent cloning of the instance * @return void */ final private function __clone() { } /** * Private unserialize method to prevent unserializing * @return void */ final private function __wakeup() { } /** * The reference to *Singleton* instance of this class * @return Singleton */ final public static function getInstance() { return isset(static::$INSTANCE) ? static::$INSTANCE : static::$INSTANCE = new static; } } //// class AB extends Singleton { protected static $INSTANCE; } class BA extends Singleton { protected static $INSTANCE; } $obj = AB::getInstance(); $obj2 = BA::getInstance(); var_dump($obj === AB::getInstance()); // bool true var_dump($obj === $obj2); // bool false
Availible also in https://gist.github.com/yuksbg/9d981ea6baf0bd8f2d92