我正在构建一个小框架,我正在尝试在我的一些对象中实现clone()方法。此方法的目标是创建给定记录的新副本,使用户更容易创建基于另一个记录的新记录。
在我看来,使用clone()和__clone()PHP方法是一个完美的场景。但究竟应该通过调用clone()返回什么?当我创建一个克隆时,即使我在__clone魔术方法中更改了一些属性,但是克隆对象之类的semms与原始对象相同。
以下是我现在所做的事情: 我的应用程序使用ascincronous通信,因此有一个由API调用的Service类;此Service类创建Record类的新实例,并创建克隆。在这个Record类中,有一个__clone魔术方法的实现,可以对数据进行一些更改,并保存新记录。
服务类中的cloneRecord方法:
public function cloneRecord($original_id) {
$originalObject = new Record($original_id);
$originalObject->load(); //access the database and retrieve the property values for this record
$cloned = clone $originalObject;
return $cloned->id; // here is the problem! See explanation below
}
记录类中的__clone方法:
public function __clone() {
$cloned = new Record();
//id and code will be generated automatically in the save() method:
$cloned->id = NULL;
$cloned->code = NULL;
//these other properties will be cloned:
$cloned->name = $this->name;
$cloned->startDate = $this->startDate;
$cloned->dueDate = $this->dueDate;
$cloned->save();
}
在此之前,一切似乎都正常。新记录将保存到数据库中,为新记录生成新ID和新代码。
我如何调用该方法:
$service = new Service();
$newRecordId = $service->cloneRecord(200);
这里发生了一些奇怪的事! 我期望从上面的行获得的是新记录的ID(可能是201)。相反,我收到相同的原始ID(200)。
这是预期的行为吗?
答案 0 :(得分:3)
检查__clone()
的{{3}}。它说:
克隆完成后,如果定义了__clone()方法,则将调用新创建的对象的__clone()方法,以允许任何需要更改的必要属性。
这意味着__clone()
将在新创建的对象的范围内运行。
您的__clone()
方法应如下所示:
public function __clone() {
//id and code will be generated automatically in the save() method:
$this->id = NULL;
$this->code = NULL;
// I would not put it here. It should happen explicitly (imo)
// But this design decision is up to you.
$this->save();
}