Property inheritance in php

I have a superclass that contains properties and methods for setting them

class Super{
    private $property;

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

then I have a subclass that should use this property

class Sub extends Super{
    private $sub_property

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

but I still get the error message

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

where am i wrong

+3
source share
3 answers

The error indicates that it is trying to find a local variable named $ property that does not exist.

To refer to the $ property in the context of the object, as you expected, you need an $thisarrow.

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

secondly, the line above will fail, because $property- privatefor the class Super. Instead protected, make it inherit.

protected $property;

Third, (thanks Merijn, I skipped this) Sub should expand Super.

class Sub extends Super
+7

$sub_property .

+3

, :

class Sub extends Super {
   // code
}
+2

Source: https://habr.com/ru/post/1786956/


All Articles