views:

426

answers:

3

Say I have a class with a private dispatch table.

$this->dispatch = array(
    1 => $this->someFunction,
    2 => $this->anotherFunction
);

If I then call

$this->dispatch[1]();

I get an error that the method is not a string. When I make it a string like this:

$this->dispatch = array(
    1 => '$this->someFunction'
);

This produces Fatal error: Call to undefined function $this->someFunction()

I have also tried using:

call_user_func(array(SomeClass,$this->dispatch[1]));

Resulting in Message: call_user_func(SomeClass::$this->someFunction) [function.call-user-func]: First argument is expected to be a valid callback.

Edit: I realized that this didn't really make sense since it is calling SomeClass::$this when $this is SomeClass. I have tried this a few ways, with the array containing

array($this, $disptach[1])

This still does not accomplish what I need.

End edit

This works if I do not have a class and just have a dispatch file with some functions. For example, this works:

$dispatch = array(
    1 => someFunction,
    2 => anotherFunction
);

I'm wondering if there is a way that I can still keep these as private methods in the class yet still use them with the dispatch table.

+5  A: 

You can store the name of the method in dispatch like:

$this->dispatch = array('somemethod', 'anothermethod');

and then use:

$method = $this->dispatch[1];
$this->$method();
Allain Lalonde
+3  A: 

The call_user_func*-Family of functions should work like this:

$this->dispatch = array('somemethod', 'anothermethod');
...
call_user_func(array($this,$this->dispatch[1]));
Waquo
It'd be neat to benchmark both approaches.
Allain Lalonde
I think I prefer your approach since it doesn't require a dereference of the method first.
Allain Lalonde
A: 

See the callback pseudo-type in the manual.

Preston