【问题标题】:PHP - Inheritable copy methodPHP - 可继承的复制方法
【发布时间】: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


【解决方案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)

【讨论】:

  • 最终在我的情况下,我宁愿使用它而不是 __clone() 重载。
【解决方案2】:

我看到了两种方法:

  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

【讨论】:

  • 你能告诉我更多关于这个return new static的信息吗?
  • TL;DR 后期静态绑定 - secure.php.net/manual/en/language.oop5.late-static-bindings.php PHP 文档很好地描述了它:)
  • 我不知道如何使用return new static进行复制,因为它只是返回调用该复制的类的新实例。
  • new static 不会进行完整复制。它只是允许您创建一个新的类实例,从中调用上下文copy()。其他用户发布了诸如new get_class($this); 之类的解决方案,这是更奇特的解决方案。要进行复制,请使用clone。请记住,它会进行浅拷贝——这意味着分配给属性的对象将通过引用进行复制。
  • 好吧,这就是我的理解。感谢您的帮助。
猜你喜欢
  • 2021-05-07
  • 2013-07-01
  • 1970-01-01
  • 2021-04-11
  • 2012-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-28
相关资源
最近更新 更多