开发者

inheriting properties in php

I have a superclass which contains properties & methods for setting them

class Super{
    private $property;

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

then I have a subclass that needs to use that property

class Sub extends Super{
    private $sub_prop开发者_开发百科erty

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

but I keep getting an error

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

where am I going wrong?


The error is saying that it's trying to find a local variable called $property which doesn't exist.

To refer to $property in object context, as you intended, you need $this and the arrow.

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

secondly, the line above will fail as is because $property is private to the Super class. Make it protected instead, so it's inherited.

protected $property;

Third, (thanks Merijn, I missed this), Sub needs to extend Super.

class Sub extends Super


You need to make your $sub_property protected instead of private.


You'll also need to specify that the subclass extends from the superclass:

class Sub extends Super {
   // code
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜