匿名函数的作用域

Scope on anonymous function

我写了一个带有匿名函数回调的路由器。

样本

$this->getRouter()->addRoute('/login', function() {
    Controller::get('login.php', $this);
});

$this->getRouter()->addRoute('^/activate/([a-zA-Z0-9\-]+)$', function($token) {
    Controller::get('activate.php', $this);
});

对于较小的代码,我想将其移动到数组中。

我用以下方法写了一个路由 class:

<?php
    namespace CTN;

    class Routing {
        private $path           = '/';
        private $controller     = NULL;

        public function __construct($path, $controller = NULL) {
            $this->path         = $path;
            $this->controller   = $controller;
        }

        public function getPath() {
            return $this->path;
        }

        public function hasController() {
            return !($this->controller === NULL);
        }

        public function getController() {
            return $this->controller;
        }
    }
?>

并且我的阵列具有新 class:

的路由路径
foreach([
    new Routing('/login', 'login.php'),
    new Routing('^/activate/([a-zA-Z0-9\-]+)$', 'activate.php');
] AS $routing) {
    // Here, $routing is available
    $this->getRouter()->addRoute($routing->getPath(), function() {

       // SCOPE PROBLEM: $routing is no more available
        if($routing->hasController()) { // Line 60
            Controller::get($routing->getController(), $this);
        }
    });
}

我现在的问题是(见评论),$routing变量在匿名函数上不可用。

Fatal error: Call to a member function hasController() on null in /core/classes/core.class.php on line 60

我该如何解决这个问题?

您可以使用父作用域中的变量 "use":

$this->getRouter()->addRoute($routing->getPath(), function() use ($routing) {

   // SCOPE PROBLEM: $routing is no more available
    if($routing->hasController()) { // Line 60
        Controller::get($routing->getController(), $this);
    }
});

参见:http://php.net/manual/en/functions.anonymous.php,以"Example #3 Inheriting variables from the parent scope"

开头的部分