我有两个类,一个事件,它包含侦听器将检查的关联会话以及要执行的方法,还有一个侦听器,它监视页面加载时的会话并执行相应的事件。
class Event
{
private $Sesh;
private $Method;
public function set(
$sesh = array(),
$method
) {
$this->Sesh = $sesh;
$this->Method = $method;
}
public function get(
) {
return [$this->Sesh,$this->Method];
}
}
class Listener
{
private $Sesh;
public function setSesh(
$foo
) {
$this->Sesh = $foo;
}
private $Event;
public function set(
$foo,
Event $event
) {
$this->Event[$foo] = $event;
}
public function dispatch(
$foo
) {
$state = true;
if(isset($this->Event[$foo]))
{
foreach($this->Event[$foo]->get()[0] as $sesh)
{
if(!isset($this->Sesh[$sesh]) || empty($this->Sesh[$sesh]))
{
$state = false;
}
}
}
// this line seems to be the cause at the method closure execution - not sure why?
return ($state) ? [true,$this->Event->get()[1]()] : [false,"Event was not triggered."];
}
}
当我运行这样的事情时:
$e = new Event;
$e->set(['misc'], function() { return 'Event method called.'; });
$l = new Listener;
$l->setSesh(array('misc' => 'example'));
$l->set('example', $e);
$l->dispatch('example');
我收到此错误:
FATAL ERROR未捕获错误:在/home/phptester.net/public_html/code.php70(5)中调用数组上的成员函数get():eval()'代码:55堆栈跟踪:#0 / home /phptester.net/public_html/code.php70(5):eval()'d code(65):Listener-> dispatch('example')#1 /home/phptester.net/public_html/code.php70(5 ):在第55行上抛出eval()#2 {main}
这似乎对应于Listener对象的dispatch方法中的方法执行,虽然我不明白它为什么这样做?我正在运行PHP 7.0
在这种情况下,我的预期输出是来自dispatch方法的返回数组,其中包含:true和一个字符串 - '调用事件方法。'
编辑:
// returns array(1) { [0]=> string(4) "misc" }
var_dump($this->Event[$foo]->get()[0]);
// returns object(Closure)#2 (0) { }
var_dump($this->Event[$foo]->get()[1]);
// returns expected string output
var_dump($this->Event[$foo]->get()[1]());