php外部对象如何使用方法,php – 如何访问方法闭包内的全局对象

博客介绍了如何使用PHP实现依赖注入模块和事件对象,以及监听器对象来处理事件。文中提到在闭包中访问全局变量$di时遇到问题,解决方案是通过`use`关键字正确引用外部变量。文章主要涉及PHP编程、匿名函数的使用以及依赖注入的概念。
摘要由CSDN通过智能技术生成

我目前有一个依赖注入模块,它允许我创建一个对象工厂:

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; });

标签:php,anonymous-function

来源: https://codeday.me/bug/20190516/1114873.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值