Php 新对象使用对象';s类实例

Php 新对象使用对象';s类实例,php,object,instance,Php,Object,Instance,今天我刚刚发现,在php中,您可以: $instance = new MyObject(); // Here $instance->getName() == 'First Instance' $instance->setName('First Instance'); // Here $newInstance->getName() == null $newInstance = new $instance(); 显然,$newInstance是一个有效的“MyObject”对

今天我刚刚发现,在php中,您可以:

$instance = new MyObject();

// Here $instance->getName() == 'First Instance'
$instance->setName('First Instance');

// Here $newInstance->getName() == null
$newInstance = new $instance();
显然,
$newInstance
是一个有效的“MyObject”对象

有人能告诉我这种方式涉及到什么,如果是或不是一个必须不要做的事情吗


伙计们

您需要使用所谓的“单例设计模式”来实现您的目标,如果我没有错的话,就是每次创建类的对象时,您都希望使用相同的对象

class Singleton {
private static $instance;

public function __construct() {
        if (isset(self::$instance)) {
            $object         = __CLASS__;
            self::$instance = new $object;
            return self::$instance;
        }
    }
}

在这里,构造函数检查是否已经存在类的实例,如果已经存在,则返回该对象本身。否则它会创建一个新的。

您想要实现什么?代码的最后一行毫无意义。我本以为它是致命的,但显然不是。我在使用一个函数,该函数在参数中接受一个对象,我不知道该类,使用一个函数获取关于该对象的更多详细信息,然后使用所有详细信息强制转换一个新的类实例。我创建了一个新类,因为这个函数是我使用API获取对象详细信息的项目的一部分,每个从这个API获取信息的函数都会返回一个“new MyObject($apiResults)”,所以我想保持这种方式,即使对于这个更通用的函数也是如此。。。