PHP5.3: "Call to undefined method" error when calling invoke from class variable

PHP thinks you want to call a method k on instance $t when you do:

$t->k(4, 5)

which is perfectly reasonable. You can use an intermediate variable to call the object:

$b = $t->k;
$b(4, 5);

See also bug #50029, which describes your issue.


When you do $test->k(), PHP thinks you are calling a method on the $test instance. Since there is no method named k(), PHP throws an exception. What you are trying to do is make PHP return the public property k and invoke that, but to do so you have to assign k to a variable first. It's a matter of dereferencing.

You could add the magic __call method to your Test class to check if there is a property with the called method name and invoke that instead though:

public function __call($method, $args) {
    if(property_exists($this, $method)) {
        $prop = $this->$method;
        return $prop();
    }
}

I leave adding the arguments to the invocation to you. You might also want to check if the property is_callable.

But anyway, then you can do

$test->k();

You can not use method syntax (like $foo->bar() ) to call closures or objects with __invoke, since the engine always thinks this is a method call. You could simulate it through __call:

function __call($name, $params) {
  if(is_callable($this->$name)) {
    call_user_func_array($this->$name, $params);
  }
}

but it would not work as-is.