php - 克隆如何创建单例的新版本?

标签 php oop object clone

我问this问题并得到了很好的解决方案。我了解如何在没有 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;
    }
}

//$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

这是怎么发生的? 克隆在这里如何工作?

最佳答案

I learned that by creating a singleton class we force a class to instantiate only once.

是的,如果我们使用我们实际设计的方法来创建对象。尽管单例的想法是在整个应用程序中共享对象的单个实例,但它仍然是对象的实例

因此,可以随意克隆对象的实例。没有什么可以阻止它被克隆。防止复制实例的方法是使用 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.

现在,如果您确实希望克隆返回相同的实例,您可以如 MaxP 所提到的,在 Singleton 类中定义 __clone() 魔术方法。

function __clone()
{
    return self::createObject();
}

这将返回正确的实例,就像对 createObject() 的任何其他调用一样。

关于php - 克隆如何创建单例的新版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34478066/

相关文章:

php - 在 php 中一起创建多个对象时哪个更有效?

javascript - 如何在 Javascript 中操作我的深层嵌套 json?

PHP 邮件不发送但没有错误

php - php中的数组冲突

javascript - PHP 表格 : If a input field is empty then do not send the table data to mail

perl - 为什么子类不继承其父类的常量?

java - IoC 容器是单例还是静态的?

php - 一行 PHP 随机字符串生成器?

perl - perl 中的继承和默认构造函数

javascript - 如何使用函数的参数来使用对象的数据?