【问题标题】:Calling $this->__construct() while cloning克隆时调用 $this->__construct()
【发布时间】:2014-09-12 23:17:00
【问题描述】:

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

我可以这样做吗?

public class MyClass {

    protected $myVar;

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

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

【问题讨论】:

  • 不如你试试看,很容易测试
  • 它有效。但我想知道这是否是重用构造函数代码的正确方法。

标签: php constructor clone


【解决方案1】:

你可以做的很好

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!

【讨论】:

    猜你喜欢
    • 2014-10-08
    • 2011-01-20
    • 2017-04-13
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多