【发布时间】:2016-08-11 09:04:30
【问题描述】:
这是我的情况:
我有一个由十几个其他人继承的类,在这个类中我有一个复制方法,它返回自身的副本。
我可以在继承类中使用此方法,但显然,该方法总是返回超类的实例,而不是从它继承的实例。
我希望我的复制方法返回 ihneriting 类的实例。
BaseEntity.php:
class BaseEntity
{
protected $id;
protected $name;
protected $active;
protected $deleted;
// ...
public function copy()
{
$copy = new BaseEntity();
$copy->id = $this->id;
$copy->name = $this->name;
$copy->active = $this->active;
$copy->deleted = $this->deleted;
return $copy;
}
}
用户.php:
class User extends BaseEntity
{
// ...
// Properties are the same as BaseEntity, there is just more methods.
}
【问题讨论】:
-
你为什么不用
clone? -
那你需要继承
User类中的copy()方法,并在那里添加你的逻辑。 -
$copy = new get_class($this)试试这个而不是$copy = new BaseEntity();
标签: php function oop inheritance copy