I have a class first where $name is set to ‘bob’. In the child class, I set $name to ‘Karen’ but it doesn’t work.
In my echo statements, the 1st one says “bob” instead of ‘Karen’. The second one, using a child class method, works though.
Why is this behavior?
class First {
public $name;
public function __construct() {
$this->name = 'bob';
}
}
class Third extends First {
public $name = 'Karen';
public function set_name ($name) {
$this->name = $name;
}
}
$instance_of_third = new Third;
$third_name = $instance_of_third->name;
echo "<br />We're looking for Karen: $third_name<br />";
// $third_name here is 'bob' from parent class
$instance_of_third->set_name("Karen");
$third_name = $instance_of_third->name;
// $third_name here is 'Karen' only after using set_name()
echo "<br />We're looking for Karen: $third_name<br />";
EDIT: I added 2 lines showing what the output was exactly.
Even though $name is explicitly set to ‘Karen’ in child class, it shows as ‘bob’ unless the set_name() function is used to change it.
Because your
Thirddoes not have it’s own constructor, it will inherit the constructor fromFirst. Inheritance creates an behaves-as relationship between supertype and subtype.So when you create a new instance of
Third, the instance will have a$nameproperty of ‘Karen’, but then the inherited constructor will get called. And that sets the name to Bob. If you don’t want that behavior in the subtype, you have to add an empty constructor toThird, e.g.demo
An alternative would be to remove the ctor (or at least not set
$namein it) and preset the$nameproperty in the parent to Bob. Then your initial idea would work, e.g.demo
Please check the chapters on Inheritance and Visibility in the PHP Manual: