继承php中的属性

Mil*_*uzz 3 php oop inheritance properties

我有一个超类,其中包含用于设置它们的属性和方法

class Super{
    private $property;

    function __construct($set){
        $this->property = $set;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

class Sub extends Super{
    private $sub_property

    function __construct(){
        parent::__construct();
        $this->sub_property = $this->property;
    }
}
Run Code Online (Sandbox Code Playgroud)

但我不断收到错误

Notice: Undefined property: Sub::$property in sub.php on line 7
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

Tes*_*rex 8

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

要在对象上下文中引用$ property,您需要$this和箭头一样.

$this->sub_property = $this->property;
Run Code Online (Sandbox Code Playgroud)

其次,上面的行将失败,因为$propertyprivateSuper班级.让它protected代替,所以它的继承.

protected $property;
Run Code Online (Sandbox Code Playgroud)

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

class Sub extends Super
Run Code Online (Sandbox Code Playgroud)

  • 如果你像这样编辑你的问题,那会非常令人困惑。将来,请接受答案或编辑您的问题,但**添加**显示您的解决方案的新代码。 (2认同)