call_user_func from within same Class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gkovacsp
Forum Newbie
Posts: 1
Joined: Sat Oct 10, 2009 11:10 am

call_user_func from within same Class

Post by gkovacsp »

I'm trying to call one class method from another method of the same class, but my variable scope is lost somewhere...
What would be the correct way for call_user_func in the below script, If I wanted to call the apple_pie method ?

Anything I tried so far ended up losing the $books array value back in the getBook method.

Code: Select all

 
class Radar2
{
var  $books = array();
var $store;
 
function getBook () {
    $this->store = "pie";
     call_user_func (array($this,"apple_".$this->store));
    print_r ($this->books);  //prints an empty array;
}
 
function apple_pie() {
    $this->books[] = "apple";
    print_r ($this->books);  //prints the array with "apple" in it;
}
}
 
 
$a = new Radar2();
$a->getBook();
 
output:

Code: Select all

Array ( [0] => apple ) 
Array ( )
User avatar
markusn00b
Forum Contributor
Posts: 298
Joined: Sat Oct 20, 2007 2:16 pm
Location: York, England

Re: call_user_func from within same Class

Post by markusn00b »

Works perfectly fine for me, my friend. :)

Mark.

P.S. The output I get is:

Code: Select all

 
array
(
    [0] => apple
)
array
(
    [0] => apple
)
 
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: call_user_func from within same Class

Post by requinix »

That's one reason why you should upgrade to PHP 5.

Code: Select all

call_user_func (array(&$this,"apple_".$this->store));
Without the & $this is a copy of the current object. apple_pie makes changes to the copy, not the original.
Post Reply