假设我有这个JS代码:
var events = ['start', 'stop', 'tick']
, obj = ... // object with events
, receiver = function(event_name, event_args){ // function to receive all events
console.log(event_name, event_args);
}
;
for(var i=0; i<events.length; i++){
obj.on(events[i], (function(event){
return function(){
return receiver(event, arguments);
};
})(events[i]));
}
我在这里做的是将所有事件路由到“接收器”功能。
我正在尝试在PHP中复制此行为,因为我已经拥有obj.on
($obj->on
)功能。
我想支持(稍微)旧的PHP版本(5.1+),所以我不能使用匿名函数(以及将变量传递给所述函数)。
这是上述代码的暂定(和不完整)版本:
$events = array('start', 'stop', 'tick');
$obj = new ... ; // object with events
function receiver($event_name, $event_args){ // function to receive all events
echo $event_name.' | '.print_r($event_args, true);
}
foreach($events as $event){
$obj->on($event, ...); // ???
// ???
return receiver($event, func_get_arguments());
// ???
}
答案 0 :(得分:0)
我可以看到的一种可能的方法是使用__invoke
:
$events = array('start', 'stop', 'tick');
$obj = new ... ; // object with events
function receiver($event_name, $event_args){ // function to receive all events
echo $event_name.' | '.print_r($event_args, true);
}
class EventRedirector {
public $event_name = '';
public $redirector = '';
public function __invoke(){
$redirector = $this->redirector;
return $redirector($this->event_name, func_get_args());
}
public function __construct($event_name, $redirector){
$this->event_name = $event_name;
$this->redirector = $redirector;
}
}
foreach($events as $event){
$obj->on($event, new EventRedirector($event, 'receiver'));
}