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.