I asked this question and got a good solution. And i understand that how an object can be created without new
(which i thought the only way to construct an object).
Now i was studying the Design patterns and learned that by creating a Singlton class we force a class to instantiate only once.
// a simple Singlton class.
class Singleton
{
private static $object = null;
private function __construct() {}
public static function createObject()
{
if (self::$object == null) {
self::$object = new Singleton();
}
return self::$object;
}
}
Now i instantiate this class.
//$obj = new Singleton(); Obviously an error
$obj1 = Singleton::createObject();
// object(Singleton)[1]
$obj2 = Singleton::createObject();
// object(Singleton)[1]
// $obj1 and $obj2 are same. Both have same id = 1
$obj3 = clone $obj1;
// object(Singleton)[2]
// $obj3 is a new instantiate. id = 2
So my question is how is this happening. how does the clone
work here.
i wish php have an singlton
keyword to create singlton class. :)
Aucun commentaire:
Enregistrer un commentaire