Created
November 11, 2015 22:21
-
-
Save yuksbg/9d981ea6baf0bd8f2d92 to your computer and use it in GitHub Desktop.
PHP Singlethon implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
*/ | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment