普通网友 2016-09-19 19:42
浏览 50

PHP - 如何继承父构造函数并包含self析构函数

in example I want to create a class with constructors, but it should also inherit parent's constructors. I will show you an example.

<?php
class Parent{
    public $var1;
    public $var2;
    public function __construct($var1, $var2){
        $this->var1 = $var1;
        $this->var2 = $var2;
    };
};
class Child1 extends Parent{
    public $var3;
    public $var4;
    public function __construct($var3, $var4){
        $this->var3 = $var3;
        $this->var4 = $var4;
    };
};
class Child2 extends Parent{
    public $var5;
    public $var6;
    public function __construct($var5, $var6){
        $this->var5 = $var5;
        $this->var6 = $var6;
    }
}
$instance = new Child1(var1, var2, var3, var4);
?>

I want to define a new instance of Child1 and Child2 using Parent constructor attributes and their own attributes. Is there a way to do that? Sorry if this seems too easy, I just started learning PHP and concept of OOP. Thanks a lot!

  • 写回答

1条回答 默认 最新

  • dov6891 2016-09-19 19:49
    关注

    From your sample code you can do:

    class Child1 extends Parent{
        public $var3;
        public $var4;
        public function __construct($var1, $var2, $var3, $var4){
            parent::__construct($var1, $var2);
            $this->var3 = $var3;
            $this->var4 = $var4;
        };
    };
    

    You can always call the method of a parent class, using the syntax parent::method when you are in the same method as parent class.

    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私