Access $this inside a route in doesn't work “Using $this when not in object context”

≯℡__Kan透↙ 提交于 2020-01-07 05:43:35

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/40362978/access-this-inside-a-route-in-doesnt-work-using-this-when-not-in-object-cont

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!