为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
长风秋雁 2021-06-11 14:07:39
我有一个父类,我将称之为“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    }}如果子类从父类扩展,为什么它不能访问父类的属性?
查看完整描述

1 回答

?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

它们是可访问的,但它们将是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(将所有内容写入两次)或不必要的重复。


查看完整回答
反对 回复 2021-06-25
  • 1 回答
  • 0 关注
  • 133 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号