使用对象的类实例

时间:2016-06-09 12:39:14

标签: 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'对象。

有人可以告诉我这种方式会涉及到什么,如果是或不是必须不这样做?

Thx mates!

1 个答案:

答案 0 :(得分:1)

你需要使用所谓的"单身设计模式"实现你的目标,如果我没有错,你每次创建一个类的对象时都要使用相同的对象。

class Singleton {
private static $instance;

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

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

相关问题