2011-12-30 4 views
2

나는 가변 함수 전에 본적이없는 것에 대한 액세스를 허용하는 함수를 가지고 있습니다.공용 변수 함수 문제

정상 기능 :

$api = api_client($special_data); 
$data = $api('get','something.json'); // notice $api() not a mistake 

이 위의 예제의 문제점 내가 내 컨트롤러의 각 기능/방법에 $ API를 변수를 createing하고 있다는 점이다. 나는 같은 것을 할 싶습니다 :

public $api; 

public function somepage(){ 
    $special_data = get_special_data_from_this_method(); 
    $this->api = api_client($special_data); 
} 

public function anotherpage(){ 
    $data = $this->api('get','something.json'); // api is not a function it is a variable function 
} 

나는 다음과 같은 작품을 찾을 않았다, 나는이 도움을 사랑하는 것이 의미가

public function somepage(){ 
    $special_data = get_special_data_from_this_method(); 
    $this->api = api_client($special_data); 
    $temp = $this->api; 
    $data = $temp('GET', '/admin/orders.json'); 
} 

희망 그것으로 만족하지 오전하지만! 당신은 먼저 임시 VAR에 떨어져 저장하지 않고이 콜백/폐쇄 전화를 사용 call_user_func을 사용할 수 있습니다

+0

시도해 보셨습니까? 작동합니까? –

+0

예 시도했지만 아무 것도 작동하지 않습니다'$ this-> api()'가 함수로 간주됩니다. '정의되지 않은 메소드 호출 mycontroller :: api()' – ThomasReggi

+0

정적으로 만들 수 있습니까? 'public static $ api;'다음과 같이 호출하십시오 :: self :: $ api ('get', 'something'); 또는 인스턴스가 필요합니까? –

답변

0

: 여기

call_user_func($this->api, $arg1, $arg2); 

는 완벽한 예입니다 :

class Foo { 
    public function __construct() { 
     // this is likely what "api_client" is returning (a closure) 
     $this->api = function ($arg1, $arg2) { 
      print "I was called with $arg1 and $arg2"; 
     }; 
    } 

    public function call_api($arg1, $arg2) { 
     return call_user_func($this->api, $arg1, $arg2); 
    } 
} 

$f = new Foo(); 
$f->call_api('foo', 'bar'); 

또는 사용하도록 예 :

public function somepage(){ 
    call_user_func($this->api, 'GET', '/admin/orders.json'); 
}