Search code examples
phpslimslim-3

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


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.


Solution

  • 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.