2016-11-01 19 views
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在函數內部。

+0

- > ..'? – jmattheis

+0

在所有我的路線功能 – JackTheKnife

+0

爲您的問題添加示例 – jmattheis

回答

2

在函數內部使用$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

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.

你使用`$這其中
相關問題