Recently in a project I am working on, I needed to store callbacks in a static member array, like so:
class Example {
private static $_callbacks = array(
'foo'=>array('Example','do_foo'),
'bar'=>array('Example','do_bar')
);
private static function do_foo() { }
private static function do_bar() { }
}
To call them, I tried the obvious (maybe even naive) syntax (inside the Example
class):
public static function do_callbacks() {
self::$_callbacks['foo']();
self::$_callbacks['bar']();
}
To my surprise, this did not work, resulting in a notice that I was accessing an undefined variable, and a fatal error stating that self::$_callbacks['foo']
needed to be callable.
Then, I tried call_user_func
:
public static function do_callbacks() {
call_user_func(self::$_callbacks['foo']);
call_user_func(self::$_callbacks['bar']);
}
And it worked!
My question is:
Why do I need to use call_user_func
as an intermediary, and not directly call them?