我正在做一个类的事件处理程序,但我想知道是否会更好地使用闭包而不是评估代码?使用闭包进行事件处理而不是使用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 –