class DiModule
{
private $Callbacks;
public function set(
$foo,
$bar
) {
$this->Callbacks[$foo] = $bar;
}
public function get(
$foo
) {
return $this->Callbacks[$foo];
}
}
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;
}
}
}
return ($state) ? [true, $this->Event[$foo]->get()[1]()] : [false, "Event was not triggered."];
}
}
这是正在执行的一个例子
$di = new DiModule();
$di->set('L', new Listener());
$di->set('E', new Event());
$di->get('E')->set(['misc'], function () { global $di; return $di; });
$di->get('L')->setSesh(array('misc' => 'active')); // not actual sessions yet
$di->get('L')->set('example', $di->get('E'));
var_dump($di->get('L')->dispatch('example'));
问题是当我尝试在闭包内访问我的全局$di时,我已经多次搜索但无法找到解决方案.
最佳答案:
您需要使用use关键字从闭包中访问外部变量.
所以这:
$di->get('E')->set(['misc'], function () { global $di; return $di; });
应该这样写:
$di->get('E')->set(['misc'], function () use ($di) { return $di; });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。