Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP Singlethon implementation
<?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
You can’t perform that action at this time.