2011-12-30 6 views
2

私は、可変関数の前に見たことのないものへのアクセスを許可する関数を持っています。パブリック変数関数の問題

通常の機能:

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

この上記の例の問題は、私は私のコントローラの各関数/メソッドの$ API変数をcreateingだということです。私はそれに満足していないですが、

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

が、これは意味が助けを大好きだ作る願って、私は次のように動作することを見つけた

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 
} 

:私はこのような何かをしたいと思います!あなたが最初の一時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'); 
}