在克隆时调用$ this-> __ construct()

时间:2014-09-12 23:17:00

标签: php constructor clone

在克隆对象时,我需要执行在对象构造期间发生的相同初始化。

我可以这样做吗?

public class MyClass {

    protected $myVar;

    public function __construct()
    {
        $this->myVar = 0
    }

    public function __clone()
    {  
        $this->__construct();
    }
}

1 个答案:

答案 0 :(得分:2)

你可以做得很好

class MyClass {

    protected $myVar;

    public function __construct()
    {
        echo "constructing!\n";
        $this->myVar = 0;
    }

    public function __clone()
    {
         echo "cloning!\n";
         $this->__construct();
    }
}

$a = new MyClass();

$b = clone $a;

输出

constructing!
cloning!
constructing!