Why a protected variable of parent class come empty?

后端 未结 2 950
萌比男神i
萌比男神i 2021-01-25 18:02

I got a protected variable in Father class, the content of this variable will change in Father class but I need to use this variable in sub classes, i.

相关标签:
2条回答
  • 2021-01-25 18:30

    You have to invoke the parent constructor.

    class Father {
       protected $body;
       function __construct(){
           $this->body = 'test';
       }
    }
    
    class Child extends Father {
       function __construct(){
           parent::__construct();
           echo $this->body;
       }
    }
    
    $c = new Father();
    $d = new Child();
    

    Reference: http://php.net/manual/en/language.oop5.decon.php

    0 讨论(0)
  • This is because you're overriding the constructor function. You must call the parent's constructor as well. More info

    class Child extends Father {
        function __construct() {
            parent::__construct();
    
            echo $this->body;
        }
    }
    
    0 讨论(0)
提交回复
热议问题