Manaus Posted April 2, 2014 Share Posted April 2, 2014 Hello,I need to make a recursive function, for printing children of children of ... of pages.I placed the function in a separate file, which I include. I get a "Error: Call to a member function get() on a non-object"This is the code: function stampafigli($id) { echo $id; // prints 1478 $messaggi = $pages->get(1478); // raises error $messaggi = $pages->get($id)->children(); if ($messaggi->count): foreach ($messaggi as $m): if($m->id): echo "$m->body" . PHP_EOL; stampafigli($m->id); endif; endforeach; endif; } Thanks for any suggestion Link to comment Share on other sites More sharing options...
kongondo Posted April 2, 2014 Share Posted April 2, 2014 (edited) There's something called variable scope within a function....Basically, a function is a closed container and is not aware of its surroundings...It only knows the things within it. Hence, you need to show it the outside world. To do that, you need to use some sort of global variable...something that is powerful enough to see the 'outside' from 'within'....that thing in PW is wire So, you can either use: wire('pages')->get();//as a function/method //or $wire->pages->get();//as a variable The same issue of scope arises when dealing with modules/class or bootstrapping PW... By the way, you don't want to be echoing within a function....use return instead (at the end)...before that...you can save stuff that you will want to output in a variable...e.g. $out = ''; //do more stuff...then we add to $out.. $out.= 'this is my cool stuff'; //do more stuff, then append to $out. $out.= 'this is even better man!'; return $out;//you can also do return $out . $another variable . $foo . $bar, etc.. //Call your function and it will output what you return-ed in the function... Edited April 2, 2014 by kongondo 5 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now