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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.