在克隆对象时,我需要执行在对象构造期间发生的相同初始化。
我可以这样做吗?
public class MyClass {
protected $myVar;
public function __construct()
{
$this->myVar = 0
}
public function __clone()
{
$this->__construct();
}
}
答案 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!