[英]Laravel root route "/" doesn't work inside prefixed routes on subdomain
[英]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
。 改用匿名函数(控制器类也可以解决):
$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
如果将Closure实例用作路由回调,则闭包的状态将绑定到Container实例。 这意味着您可以通过
$this
关键字访问Closure内部的DI容器实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.