ryy705 Posted November 20, 2008 Share Posted November 20, 2008 Hello, I expected the following code to display a:40 b:10 but it displays a: 30, b: 10. It seems that only $this->a is getting passed to parent::changeValue() instead of the sum of $this->a + $this->b. Whys is that? <?php 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(); Link to comment https://forums.phpfreaks.com/topic/133449-why-does-this-happen/ Share on other sites More sharing options...
DyslexicDog Posted November 20, 2008 Share Posted November 20, 2008 public function changeValue($b) { $this->b = 10; you reset the value of $this->b to 10 every time you call that function. Pretty sure that's where your problem is. Link to comment https://forums.phpfreaks.com/topic/133449-why-does-this-happen/#findComment-694113 Share on other sites More sharing options...
genericnumber1 Posted November 20, 2008 Share Posted November 20, 2008 when you pass a value to changeValue($b) in the subclass, you don't actually do anything with it. Perhaps you meant to do $this->b = $b instead of 10? Link to comment https://forums.phpfreaks.com/topic/133449-why-does-this-happen/#findComment-694114 Share on other sites More sharing options...
bogeyman Posted November 20, 2008 Share Posted November 20, 2008 Maybe you can try this. Change this line. parent::changeValue($this->a + $this->b); To parent::changeValue($this->a + $b); Link to comment https://forums.phpfreaks.com/topic/133449-why-does-this-happen/#findComment-694116 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.