【发布时间】: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