繁体   English   中英

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

[英]Parent's protected properties inaccessible to child object

我有一个父类,我将其称为“ 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

    }

}

如果子类继承自父类的属性,为什么子类无法访问呢?

它们是可访问的,但它们将为null因为它们不会从子对象传递到父构造函数:

(new ChildClass(1,2))->anotherFakeMethod();

砂箱

产量

NULL

在这种情况下,您的班级会产生null的预期结果。 好吧,它根据编码方式产生了我期望的结果。

要修复它,您必须通过子级的构造函数将该数据传递回父类,或删除子级的构造函数。 像这样:

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(两次编写所有内容)或不必要的重复。

干杯!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM