这是我的情况:
我有一个由十几个其他人继承的类,在这个类中我有一个复制方法,它返回自己的副本。
我可以在继承类中使用此方法,但显然,该方法总是返回超类的实例,而不是从它继承的实例。
我希望我的copy方法返回一个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;
}
}
User.php:
class User extends BaseEntity
{
// ...
// Properties are the same as BaseEntity, there is just more methods.
}
答案 0 :(得分:1)
我看到两种方法:
clone
- 它会制作对象的浅表副本使用static
创建新对象
<?php
class BaseEntity {
public function copy() {
return new static;
}
}
class User extends BaseEntity {
}
$user = new User;
var_dump($user->copy());
此代码的结果:https://3v4l.org/2naQI
答案 1 :(得分:1)
实现目标的另一种方法:
<?php
class BaseEntity
{
protected $id;
public function copy()
{
$classname = get_class($this);
$copy = new $classname;
return $copy;
}
}
class Test extends BaseEntity
{
}
$test = new Test;
$item = $test->copy();
var_dump($item); // object(Test)