在symfony中创建另一个实例的空副本

问题描述 投票:-2回答:1

是否可以在没有其值的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()创建它的新实例,但是是否存在以这种方式执行此操作的方法?

symfony copy entity instance clone
1个回答
0
投票

您可以覆盖__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
© www.soinside.com 2019 - 2024. All rights reserved.