Access $this inside a route in doesn't work “U

2019-09-06 02:34发布

I'm trying to use $this inside a function of a route, when I'm doing this, it gives me the following error:

Using $this when not in object context

Here's the code:

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();

I have tried to implement it based on this.

Why it doesn't work to use $this inside the function and how can I use $this inside a function.

标签: php slim slim-3
1条回答
在下西门庆
2楼-- · 2019-09-06 03:15

It is not possible to use $this inside the function when declaring it with a string. Use an anonymous function instead (a controller-class would also be a fix):

$app->get('/', function ($request, $response) {
    $response->write('REST API v1');
    $this->logger->addInfo("Something interesting happened"); 
    return $response;
});

See: 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.

查看更多
登录 后发表回答