2016-11-01 5 views
0

$this을 경로의 기능 안에서 사용하려고 할 때,이 작업을 수행 할 때 다음과 같은 메시지가 표시됩니다 오류 : 나는 this에 기반을 구현하기 위해 노력했다

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

:

Using $this when not in object context 

여기에 코드입니다.

왜 함수 내에 $this을 사용하지 못하고 함수 내에 $this을 사용할 수 있습니까?

+0

-> ...'? – jmattheis

+0

내 모든 경로 기능에서 – JackTheKnife

+0

질문에 예제를 추가하십시오 – jmattheis

답변

2

문자열로 선언 할 때 함수 내에 $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.