Access $this inside a route in doesn#39;t work quot;Using $this when not in object contextquot;(在不在对象上下文中时使用$This访问不起作用的路由中的$This(q;))
问题描述
我尝试在路由的函数中使用$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 SlimApp();
/** my routes here **/
$app->get('/', 'api');
$app->run();
我已尝试基于this实现它。
为什么在函数内使用$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
如果使用闭包实例作为路由回调,则闭包的状态将绑定到Container实例。这意味着您将可以通过
$this
关键字访问闭包内部的DI容器实例。
这篇关于在不在对象上下文中时使用$This访问不起作用的路由中的$This(&q;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!