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. Quote Link to comment 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); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.