doulao1966 2017-03-21 17:12
浏览 30
已采纳

匿名函数的范围

I had write a Router with anonymous function callback.

Sample

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

for smaller code, i want to move it to an Array.

I had write a Routing class with following methdos:

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

And my array has the routing paths with the new 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);
        }
    });
}

My current problem is (see the comments), the $routing variable is on the anonymous function not available.

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

how i can solve this problem?

  • 写回答

1条回答 默认 最新

  • dongwolu5275 2017-03-21 17:16
    关注

    You can use a variable from the parent scope by using "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);
        }
    });
    

    see: http://php.net/manual/en/functions.anonymous.php , the part that starts with "Example #3 Inheriting variables from the parent scope"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题