猿问

子对象无法访问父对象的受保护属性

我有一个父类,我将称之为“ParentClass”,还有一个子类(从它扩展而来),我将称之为“ChildClass”。


ParentClass 具有我希望 ChildClass 访问的受保护属性 $prop1 和 $prop2。但我从他们那里得到了 NULL。


ParentClass 有一个 __construct() 方法,它设置通过依赖注入接收的属性。


ParentClass 从其方法之一实例化 ChildClass。


ChildClass 覆盖父构造函数,但在其自己的 __construct() 方法中不包含任何代码。


我已经用 var_dump($this->prop1) 测试了父类的属性。它返回我期望的值。


但是,如果我从子类中 var_dump($this->prop1) ,我会得到 NULL。


class ParentClass {


    protected $prop1;


    protected $prop2;


    public function __construct($prop1, $prop2) {


        $this->prop1 = $prop1;


        $this->prop2 = $prop2;


    }


    public function fakeMethod() {


        $child = new ChildClass;

        $child->anotherFakeMethod();


        // logic


    }


}

class ChildClass extends ParentClass {


    public function __construct() {


        // this overrides the parent constructor


    }


    public function anotherFakeMethod() {


        $prop1 = $this->prop1;

        $prop2 = $this->prop2;


        var_dump($this->prop1);

        // returns NULL


    }


}

如果子类从父类扩展,为什么它不能访问父类的属性?


长风秋雁
浏览 135回答 1
1回答

一只斗牛犬

它们是可访问的,但它们将是null因为它们没有从子进程传递给父构造函数:(new ChildClass(1,2))->anotherFakeMethod();沙盒输出NULLnull在这种情况下,您的课程会产生预期的结果。那么它会根据它的编码方式产生我期望的结果。要修复它,您必须通过子类的构造函数将该数据传递回父类,或者删除子类的构造函数。像这样:class ChildClass extends ParentClass {    public function __construct($prop1, $prop2) {         parent::__construct($prop1, $prop2);    }....}以上改动后:(new ChildClass(1,2))->anotherFakeMethod();输出int(1)沙盒这是我对这一行的期望,因为它基本上是构造函数中使用的第一个参数:var_dump($this->prop1);如果您知道子类中的内容,您也可以这样做:public function __construct() {     parent::__construct(1, 2); //say I know what these are for this child}您当然可以在新的构造函数中手动设置它们,但在这种情况下,这将是 WET(将所有内容写入两次)或不必要的重复。
随时随地看视频慕课网APP
我要回答