Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Non OO functions calling objects 2

Status
Not open for further replies.

senorcai

Programmer
Jul 19, 2006
7
GB
Hi All

I've been having all sorts of issues just trying to get a LIFO Stack working in PHP and am not quite sure why. In my latest incarnation I've actually build a Stack class. However, when I try to call the push function (and probably the pop too if it ever got that far) it just returns the following error:
Code:
Fatal error:  Call to a member function push() on a non-object in...
When I call the stack's functions from the procedural code I have no problems, however when it is called from a function it won't work. I've tried declaring the class instance as global but that doesn't seem to work either. My code is below:
Code:
class LIFOStack{
	var $elementData;

	function LIFOStack(){
		$this->elementData = array();
	}

	function pop(){
		return array_pop($this->elementData);
	}

	function push($item) {
		array_push($this->elementData, $item);
		return $item;
	}
}

global $stack;
$stack = new LIFOStack;
[b]$stack->push("hello");
echo($stack->pop()); //this returns 'hello' fine.[/b]

function startElement($parser, $name, $attribs){
	if($name == "RESULT")
		echo("<Property>");
	else if(count($attribs)){
		//echo("<$attribs['NAME']>"); - TODO: shouldn't we be able to do something like this?!
		foreach ($attribs as $k => $v) 
			if($k == "NAME"){
				echo("<$v>");
				[b]$stack->push($v); //this always throws the error[/b]
			}
	}
}
Any ideas much appreciated!
SenorCai
 
I don't see a global declaration for the $stack variable in your function...? Or are you using a differant one?

 
Doesn't global $stack; do that for you? If not then that's most likely the problem, though I wouldn't have expected there to be a need to declare it global anyway - that was more through a matter of desperation.

I just searched google and found another way of declaring the global variables so I've replaced
Code:
global $stack;
$stack = new LIFOStack;
with
Code:
$GLOBALS['stack'] = new LIFOStack;
Annoyingly though I'm still getting exactly the same results as before - outside a function it'll return 'hello' but within a function it throws up the same error.
 
as tarwn inferred, put the global $stack inside the function.
 
I didn't realise you have to explicitly type global $stack in every method in which you need to use it. Problem sorted now thank you!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top