Inherit the properties in PHP

I have a super class which contains properties & methods to set them

class Super{
private $property;

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

Then I There is a subclass that needs to use this property

class Sub extends Super{
private $sub_property

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

But I keep getting errors p>

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

Where did I go wrong?

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

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

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

Secondly, the above line will fail because $property is a private property of the Super class. Change it to make it protected, so it is inherited.

protected $property;

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

class Sub extends Super

I have a super class which contains properties & methods to set them

class Super{
private $property;

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

Then I have a subclass that needs to use this property

class Sub extends Super{
private $sub_property

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

But I keep getting errors

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

Where did I go wrong?

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

To To refer to $property in the object context according to your intentions, you need $this and arrows.

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

< p>Secondly, the above line will fail because $property is a private property of the Super class. Change it to make it protected, so it is inherited.

protected $property; 

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

class Sub extends Super

Leave a Comment

Your email address will not be published.