Returning a Method Variable

Hello,

I’m very new to PHP OOP coding practices.

I’m trying to return a method variable and it’s not working. This is a very basic example of what I’m trying to do. I want to return the method variable value so I can display it on the page using some HTML.

Can anyone please tell me what I’m doing wrong? Is it possible to access a method variable value from outside the class method once it’s created?

Here’s my code:


class Tracker {
	function increase($newValue=0) {
		$newValue ++;
		// THIS PRINTS 11
		echo "<br />inside class method: ".$newValue."<br />";
		return $newValue;
	}
}

$tracker = new Tracker();
$tracker->increase(10);
// This prints NULL
print "<pre>";
var_dump($tracker->$newValue);
print "</pre>";

When I run the code, I get:

inside class method: 11
Fatal error: Cannot access empty property in…

I’m using PHP 5.2 and Zend Server CE for a dev environment.

Thanks In Advance,
OOPNoob

Not a problem. Have fun!
You’ll be able to drop the Noob part in no time!

Ooh, wait you’re printing the returned value from your method in both instances. Try it with the same output method you used first time around.
Define it as 0 on your second class line. Then when you var_dump it you should get something like int (0) I believe.

Hello,

Thank you for your time and insight. Your suggestion worked! I guess I must have overlooked that lesson in OOP. My bad.

Solution:

class Tracker {
	public $newValue;
	function increase($newValue=0) {
		$newValue ++;
		// THIS PRINTS 11
		echo "<br />inside class method: ".$newValue."<br />";
		return $newValue;
	}
}

$tracker = new Tracker();
$returned = $tracker->increase(10);
// THIS PRINTS 11
print "outside class method: ".$returned."<br />";

And my screen says:
inside class method: 11
outside class method: 11

Thanks again!
OOPNoob

$newValue is not a class var, so there’s nothing named that for your PHP to dump.

Define it as like the second line of class code.