0

我正在尝试$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内部使用。

4

1 回答 1

3

$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这意味着您将可以通过关键字访问闭包内的 DI 容器实例。

于 2016-11-01T15:25:08.977 回答