可继承的复制方法


PHP - Inheritable copy method

我的情况是:
我有一个类,它被许多其他类继承,在这个类中,我有一个copy方法,它返回自身的副本。
我可以在继承类中使用这个方法,但显然,这个方法总是返回超类的一个实例,而不是从它继承的那个。

我希望我的复制方法返回一个继承类的实例。

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:

class User extends BaseEntity
{
    // ...
    // Properties are the same as BaseEntity, there is just more methods. 
}

实现目标的另一种方法:

<?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)

我看到了两种方法:

  1. 使用clone -它将使您的对象的浅拷贝
  2. 使用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