2013-04-12 158 views
1

比方說,我有這樣的JS代碼: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

一個我看到的卻是使得__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')); 
}