Skip to content

Instantly share code, notes, and snippets.

@yuksbg
Created November 11, 2015 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuksbg/9d981ea6baf0bd8f2d92 to your computer and use it in GitHub Desktop.
Save yuksbg/9d981ea6baf0bd8f2d92 to your computer and use it in GitHub Desktop.
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