, Singleton. :
Change __construct and __clone to private, so calling the new TestClass () will fail!
Now create a class that will create a new instance of your object or return an existing one ...
Example:
abstract class Singleton
{
final private function __construct()
{
if(isset(static::$instance)) {
throw new Exception(get_called_class()." already exists.");
}
}
final private function __clone()
{
throw new Exception(get_called_class()." cannot be cloned.");
}
final public static function instance()
{
return isset(static::$instance) ? static::$instance : static::$instance = new static;
}
}
Then try extending this class and defining a static instance variable $
class TestClass extends Singleton
{
static protected $instance;
}
Now try the following:
echo get_class($myinstance = TestClass::instance();
echo get_class($mysecondinstance = TestClass::instance());
Done
source
share