公共变量函数问题


Public variable function issue

我有一个函数,允许访问一些我以前从未见过的东西一个变量函数

正常功能:

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

上面这个例子的问题是,我在控制器的每个函数/方法中创建了$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');
}

希望这是有意义的,会喜欢的帮助!

你可以使用use call_user_func来调用这个回调/闭包,而不需要先保存到一个临时变量:

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