如何在方法闭包中访问全局对象

How to access a global object inside a method closure

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

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

您的 DiModule class 的 set()get() 方法的名称/实现似乎不匹配。

您发布的代码有这些方法:

function get($foo, $bar) { /* ... */ }
function set($foo) { /* ... */ }

最有可能是:

function get($foo) { /* ... */ }
function set($foo, $bar) { /* ... */ }

为了减少这些错误的可能性,给你的参数起有意义的名字(比如 $key$value)而不是通用的 $foo$bar。这样就更容易被发现了。