Eggzorcist Posted December 30, 2010 Share Posted December 30, 2010 I've made my first object that will addition an array but it doens't seem to be working as it echo's out 0. here is my script <?php class A { public $sum = 0; function addition($values){ foreach ($values as $numbers){ $this->sum = $number + $this->sum; } echo $this->sum; } } $a = new A(); $array = array(10, 15, 25); echo $a->addition($array); ?> I don't see what I'm doing wrong. Any direction would be greatly appreciated. Link to comment https://forums.phpfreaks.com/topic/223029-new-to-oop-quick-help/ Share on other sites More sharing options...
Zurev Posted December 30, 2010 Share Posted December 30, 2010 Missing an s on the $numbers variable where you perform the addition, outside of that, a couple of things. It's generally bad practice to explicitly echo out values in your functions, since you do that you could display your answer without the echo in the call. But really, you should set inside the function to "return $this->sum;", and then keep your call the same. So I quickly switched it to: class A { public $sum = 0; function addition($values){ foreach ($values as $number){ $this->sum += $number; } return $this->sum; } } $a = new A(); $array = array(10, 15, 25); echo $a->addition($array); Link to comment https://forums.phpfreaks.com/topic/223029-new-to-oop-quick-help/#findComment-1153115 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.