1

Say I have the following:

class C {
    private $f;

    public function __construct($f) {
        $this->f = $f;
    }

    public function invoke ($n) {
        $this->f($n); // <= error thrown here
    }
}

$c = new C(function ($m) {
    echo $m;
});

$c->invoke("hello");

The above throws the following error:

Fatal error: Call to undefined method C::f()

And I'm guessing that it's because I'm trying to invoke the callback function $this->f using the same syntax one would invoke an object's member functions.

So what's the syntax that allows you to invoke a function which is stored in a member variable?

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
  • 2
    Shot in the dark: `($this->f)($n)`. If that doesn't work, try `$f = $this->f; $f($n);`. – cdhowie Aug 14 '11 at 20:52
  • +1 Oh, the latter worked! But that seems like a strange way to do it... – Andreas Grech Aug 14 '11 at 20:54
  • possible duplicate of [Calling closure assigned to object property directly](http://stackoverflow.com/questions/4535330/calling-closure-assigned-to-object-property-directly) – Gordon Aug 14 '11 at 20:57

1 Answers1

1

You need to use call_user_func:

public function invoke ($n) {
    call_user_func($this->f, $n);
}

UPDATE

Christian points out that call_user_func is very slow, and that this is faster:

function my_call_user_func($f) {
    $f();
}
Matthew
  • 15,464
  • 2
  • 37
  • 31