Please tell me why:
class ClassOne {
protected $a = 10;
public function changeValue($b) {
$this->a = $b;
}
}
class ClassTwo extends ClassOne {
protected $b = 10;
public function changeValue($b) {
$this->b = 10;
parent::changeValue($this->a + $this->b);
}
public function displayValues() {
print "a: {$this->a}, b: {$this->b}\n";
}
}
$obj = new ClassTwo();
$obj->changeValue(20);
$obj->changeValue(10);
$obj->displayValues();
Prints a: 30 and b: 10.
I would appreciate an elaborate response. Thank you 🙂
On a side note: This is actually an exam question I’ve looked over and did not quite understand it. Thank you for your responses.
I don’t know how to summarize this execution besides “it’s executing the logic as you’ve written”.
I’ve added comments to each call to show the intermediary steps:
You may be confused by this:
Because
$bis never assigned to anything. So it doesn’t matter what you pass tochangeValue, you’ll always get30, 10when you callchangeValuetwice.E.g. :
Will still output
a: 30 and b: 10