2

I have a function that permits access to something I've never seen before a variable function.

normal functionality:

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

The problem with this above example is that I am createing the $api variable in each function / method of my controller. I would like to do something like this:

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
}

I did find that the following works, although I am not satisfied with it

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

Hope this makes sense would love the help!

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • Have you tried it? Does it work? – Michael Berkowski Dec 30 '11 at 04:26
  • Yes I have tried it and no it does not work `$this->api()` is regarded as a function the error is `Call to undefined method mycontroller::api()` – ThomasReggi Dec 30 '11 at 04:27
  • Can you make it static? `public static $api;` Then call as `self::$api('get','something');` Or do they need to be instance-specific? – Michael Berkowski Dec 30 '11 at 04:29
  • Not keen on the difference even after looking through http://stackoverflow.com/questions/151969/php-self-vs-this but I tried it and its not working either `Undefined variable: api` and `Function name must be a string in ...` – ThomasReggi Dec 30 '11 at 04:34
  • Static properties and methods are shared by all instances of a class. Each object doesn't get its own, so if one changes, it is reflected in all class instances (objects). I forgot one part above. I'll put it in as an answer. – Michael Berkowski Dec 30 '11 at 04:37
  • The part missed in my comment was the static assignment `self::$api = api_client()` instead of `$this->api = api_client()` – Michael Berkowski Dec 30 '11 at 04:39

1 Answers1

0

You can use use call_user_func to call this callback/closure without having the save off to a temp var first:

call_user_func($this->api, $arg1, $arg2);

Here's a complete example:

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

Or, to use your example:

public function somepage(){
    call_user_func($this->api, 'GET', '/admin/orders.json');
}
Adam Wagner
  • 15,469
  • 7
  • 52
  • 66