【问题标题】:Scope on anonymous function匿名函数的作用域
【发布时间】:2017-08-13 12:30:46
【问题描述】:

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

示例

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

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

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

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

我的数组有新类的路由路径:

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

我当前的问题是(参见 cmets),$routing 变量在匿名函数上不可用。

致命错误:在第 60 行的 /core/classes/core.class.php 中,在 null 上调用成员函数 hasController()

我该如何解决这个问题?

【问题讨论】:

    标签: php scope anonymous-function


    【解决方案1】:

    您可以通过使用“使用”来使用父作用域中的变量:

    $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,以“示例#3 从父作用域继承变量”开头的部分

    【讨论】:

      猜你喜欢
      • 2011-03-11
      • 2011-09-10
      • 1970-01-01
      • 2011-12-15
      • 2011-06-22
      • 2011-12-11
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      相关资源
      最近更新 更多