dt4320279 2014-06-15 05:44
浏览 33
已采纳

PHP - 将父类实例的所有属性传递给子实例

I have a method which creates an instance of a child class and copies its properties over. I achieve this with $child->property = $this(parent)->propery with each property. Is there a way to do this all in one bite without having to repeat the code to define each individual property?

Extended example:

class parent {
    public  $foo
            $bar
            $gib

    public function foobar() {
        $child = new child;
            $child->foo = $this->foo;
            $child->bar = $this->bar;
            $child->gib = $this->gib;
    }
}

class child extends parent {

}
  • 写回答

2条回答 默认 最新

  • dongyuan8024 2014-06-15 05:54
    关注

    You are defeating the purpose of inheritance by putting the logic of the child constructor inside the parent. You don't want the parent class to ever have visibility on what the type of the child is.

    Consider the following code.

    class Parent {
    
      protected $foo;
      protected $bar;
    
      public function __construct($foo, $bar) {
        $this->foo = $foo;
        $this->bar = $bar;
      }
    }
    
    class Child extends Parent {
    
      public function __construct($foo, $bar) {
        parent::__construct($foo, $bar);
      }
    }
    

    Here, the child takes it upon itself to instantiate the properties of the parent class. It is the responsibility of the child class to do so.

    Related reading - http://www.php.net//manual/en/language.oop5.decon.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记