2011-12-30 41 views
2

我有一個函數,允許訪問我在變量函數前從未見過的東西。公用變量函數問題

正常功能:

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

與此上面的例子中的問題是,我的createing $ API變量在我的控制器的各功能/方法。我願做這樣的事情:

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'); 
} 

希望這是有道理很想幫助!

+0

你試過了嗎?它工作嗎? – 2011-12-30 04:26:27

+0

是的,我試過了,沒有它不工作'$ this-> api()'被認爲是一個函數,錯誤是'調用未定義的方法mycontroller :: api()' – ThomasReggi 2011-12-30 04:27:40

+0

你可以使它靜態嗎? 'public static $ api;'然後調用'self :: $ api('get','something');'或者它們需要實例化? – 2011-12-30 04:29:19

回答

0

您可以根據call_user_func來調用這個回調/關閉,而無需關閉保存到臨時VAR第一:

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'); 
}