2

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.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
mk.
  • 26,076
  • 13
  • 38
  • 41

2 Answers2

9

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
  • 91,574
  • 70
  • 187
  • 238
5

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
  • 840
  • 1
  • 5
  • 6