Why a protected variable of parent class come empty?

后端 未结 2 949
萌比男神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

提交回复
热议问题