Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a dispatch table within a class in PHP?

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.

like image 213
mk. Avatar asked Feb 03 '26 23:02

mk.


1 Answers

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();
like image 102
Allain Lalonde Avatar answered Feb 05 '26 12:02

Allain Lalonde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!