2011-12-30 70 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'); 
}