公共变量函数问题

时间:2011-12-30 04:23:38

标签: php model-view-controller class codeigniter

我有一个函数允许访问我在变量函数之前从未见过的东西。

正常功能:

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

希望这是有道理的,希望得到帮助!

1 个答案:

答案 0 :(得分:0)

您可以使用use call_user_func来调用此回调/闭包,而不必先将保存设置为temp 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');
}