在路由中访问 $this 无效 "Using $this when not in object context"
Access $this inside a route in doesn't work "Using $this when not in object context"
我试图在路由函数中使用 $this
,当我这样做时,出现以下错误:
Using $this when not in object context
代码如下:
function api($request, $response) {
$response->write('REST API v1');
$this->logger->addInfo("Something interesting happened");
return $response;
}
$app = new \Slim\App();
/** my routes here **/
$app->get('/', 'api');
$app->run();
我尝试在this的基础上实现它。
为什么在函数内部使用 $this
不起作用以及如何在函数内部使用 $this
。
当用字符串声明函数时,不能在函数内部使用 $this
。改为使用匿名函数(控制器-class 也可以修复):
$app->get('/', function ($request, $response) {
$response->write('REST API v1');
$this->logger->addInfo("Something interesting happened");
return $response;
});
参见:http://www.slimframework.com/docs/objects/router.html
If you use a Closure instance as the route callback, the closure’s state is bound to the Container instance. This means you will have access to the DI container instance inside of the Closure via the $this
keyword.
我试图在路由函数中使用 $this
,当我这样做时,出现以下错误:
Using $this when not in object context
代码如下:
function api($request, $response) {
$response->write('REST API v1');
$this->logger->addInfo("Something interesting happened");
return $response;
}
$app = new \Slim\App();
/** my routes here **/
$app->get('/', 'api');
$app->run();
我尝试在this的基础上实现它。
为什么在函数内部使用 $this
不起作用以及如何在函数内部使用 $this
。
当用字符串声明函数时,不能在函数内部使用 $this
。改为使用匿名函数(控制器-class 也可以修复):
$app->get('/', function ($request, $response) {
$response->write('REST API v1');
$this->logger->addInfo("Something interesting happened");
return $response;
});
参见:http://www.slimframework.com/docs/objects/router.html
If you use a Closure instance as the route callback, the closure’s state is bound to the Container instance. This means you will have access to the DI container instance inside of the Closure via the
$this
keyword.