Jump to content

new to OOP, quick help


Eggzorcist

Recommended Posts

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

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);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.