是否可以在没有其值的symfony中复制实体的实例?例如我有以下实体
class Dog{
private $_name;
__construct(){
$this->_name = null;
}
}
setName($name){
$this->_name = $name;
return $this;
}
getName(){
return $this->_name;
}
}
$billy = new Dog();
$billy->setName('billy')
我可以获取副本“ $ billy”来获取名称参数不带“ billy”值的新实例吗?
我知道我可以复制它并设置一个新名称,也可以使用new Dog()创建它的新实例,但是是否存在以这种方式执行此操作的方法?
您可以覆盖__clone
实体内部的魔术PHP方法Dog
以重置$name
值
class Dog {
private $name;
public function __construct() {
$this->name = null;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getName() {
return $this->name;
}
public function __clone() {
$this->name = null;
}
}
$billy = new Dog();
$billy->setName('Billy');
$billy->getName(); // Returns 'Billy'
$clonedBilly = clone $billy;
$clonedBilly->getName(); // Returns null