在不在对象上下文中时使用$This访问不起作用的路由中的$This(&q;)

人气:935 发布:2022-10-16 标签: php slim slim-3

问题描述

我尝试在路由的函数中使用$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容器实例。

390