Page 1 of 1

call_user_func from within same Class

Posted: Sat Oct 10, 2009 5:20 pm
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 ( )

Re: call_user_func from within same Class

Posted: Sun Oct 11, 2009 2:54 pm
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
)
 

Re: call_user_func from within same Class

Posted: Sun Oct 11, 2009 4:24 pm
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.