Php 克隆如何创建新版本的单例?
我问了一个问题,得到了一个很好的答案。我了解如何在没有Php 克隆如何创建新版本的单例?,php,oop,object,clone,Php,Oop,Object,Clone,我问了一个问题,得到了一个很好的答案。我了解如何在没有new的情况下创建对象(我认为这是构建对象的唯一方法) 我了解到,通过创建一个单例类,我们强制一个类只实例化一次 // a simple singleton class. class Singleton { private static $object = null; private function __construct() {} public static function createObject()
new
的情况下创建对象(我认为这是构建对象的唯一方法)
我了解到,通过创建一个单例类,我们强制一个类只实例化一次
// a simple singleton 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;
}
}
这是怎么发生的?
clone
在这里是如何工作的?如果要阻止克隆单例,请添加私有方法\uu clone私有函数\uu clone(){}
我了解到,通过创建一个单例类,我们强制一个类只实例化一次
// a simple singleton 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;
}
}
是的,如果我们使用我们实际设计的方法来创建对象。尽管singleton的思想是在整个应用程序中共享对象的单个实例,但它仍然是对象的实例
因此,可以随意克隆对象的实例。没有什么能阻止它被克隆。防止复制实例的是使用createObject()
方法。(对于记录,最好将其命名为getObject()
)
因此,按顺序:
$obj1 = Singleton::createObject();
// the method call creates the instance with new
// assigns it to the property of the singleton class
// then returns it
$obj2 = Singleton::createObject();
// the method returns the instance from the first method call
// as it is still defined in the static property
// BOTH $obj1 and $obj2 are the same instance of an object
$obj3 = clone $obj1;
// here, we use the clone keyword.
// this has nothing to do with our singleton, yet
// it simply clones an instance of an object.
// $obj1 is an instance of an object. It is therefore cloned.
现在,如果您真的希望clone返回相同的实例,那么可以像MaxP提到的那样,在Singleton
类中定义\uu clone()
魔术方法
function __clone()
{
return self::createObject();
}
它将返回正确的实例,就像对createObject()
的任何其他调用一样