当前位置 : 主页 > 手机开发 > 其它 >

继承php中的属性

来源:互联网 收集:自由互联 发布时间:2021-06-19
我有一个超类,其中包含属性设置它们的方法 class Super{ private $property; function __construct($set){ $this-property = $set; }} 然后我有一个需要使用该属性的子类 class Sub extends Super{ private $sub_property
我有一个超类,其中包含属性&设置它们的方法

class Super{
    private $property;

    function __construct($set){
        $this->property = $set;
    }
}

然后我有一个需要使用该属性的子类

class Sub extends Super{
    private $sub_property

    function __construct(){
        parent::__construct();
        $this->sub_property = $this->property;
    }
}

但我不断收到错误

Notice: Undefined property: Sub::$property in sub.php on line 7

我哪里错了?

错误是说它正在尝试找到一个名为$property的局部变量,该变量不存在.

要按照您的意图在对象上下文中引用$property,您需要$this和箭头.

$this->sub_property = $this->property;

其次,上面的行将失败,因为$property是Super类的私有属性.改为使其受到保护,因此它是继承的.

protected $property;

第三,(感谢Merijn,我错过了这个),Sub需要扩展Super.

class Sub extends Super
网友评论