我正在做一個類的事件處理程序,但我想知道是否會更好地使用閉包而不是評估代碼?使用閉包進行事件處理而不是使用eval()會更好嗎?
我使用eval()的唯一原因僅僅是因爲它能夠訪問類中的所有內容(它真的非常不安全:D),但我不知道閉包是否可以。
,如果我做了這樣的事情:
<?php
class SomethingCool {
protected $handlers;
public function addHandler($cmd, closure $func) {
$this->handlers[$cmd][] = $func;
}
public function handle($cmd) {
if(!isset($this->handlers[$cmd]))
return false;
foreach($this->handlers[$cmd] as $func)
$func();
}
}
?>
<?php
$wut = new SomethingCool();
$wut->addHandler('lol', function() use($wut) {
$wut->handle('lol');
}
);
?>
它會執行沒有錯誤? 我會自己測試,但目前我無法進行測試。
除了引用'unset'引起的明顯錯誤... –
'$ this'應該引用什麼? –
請參閱:http://php.net/manual/en/functions.anonymous.php#107949 –