Php 匿名函数的作用域
我写了一个带有匿名函数回调的路由器 样本Php 匿名函数的作用域,php,scope,anonymous-function,Php,Scope,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', $th
$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;
}
}
?>
我当前的问题是(请参阅注释),$routing
变量位于匿名函数上,不可用
致命错误:在第60行的/core/classes/core.class.php中调用null上的成员函数hasController()
如何解决此问题?您可以通过使用“use”来使用父范围中的变量:
请参阅:,以“示例3从父范围继承变量”开头的部分。您可以使用“使用”从父范围使用变量: 请参见:,以“示例#3从父范围继承变量”开头的部分
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);
}
});
}
$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);
}
});