Reputation: 663
Working a lot with JS I have come to love closures, so I was pleased to learn that there are closures in PHP also. However I just can't get this stuff to work, what's wrong with this piece of code?
class Foo {
public $Bar;
public function Foo() {
$this->Bar = function() { echo "Hello World"; };
}
};
$F = new Foo();
$F->Bar();
I keep getting PHP Fatal error: Call to undefined method Foo::Bar()
errors.
Upvotes: 2
Views: 488
Reputation: 122538
PHP has separation between methods and fields. In fact, you can have a method and a field of the same name at the same time:
class Foo {
public $Bar;
function Bar() { echo "hello\n"; }
};
$F = new Foo();
$F->Bar = 42;
$F->Bar(); // echoes "hello"
So you can see that, to avoid ambiguity, there must be a separate syntax between calling a method with that name, and accessing a field with that name and then calling that as a function.
If PHP had better syntax, they would support ($F->Bar)()
, i.e. function call operator on any expression, but currently only variables can be "called".
Upvotes: 1
Reputation: 9121
This has been discussed a lot on SO already (see e.g. this answer). This should do the trick:
$b = $f->Bar;
$b();
Yes, it is that stupid. You could use call_user_func()
to put in in one line (see jlb's answer to this question), but the ugliness remains.
Upvotes: 5
Reputation: 20010
If you want a one-line solution to replace
$F->Bar()
try this:
call_user_func($F->Bar);
Upvotes: 2
Reputation: 8639
PHP isn't liking the $F->Bar
notation for accessing the closure.
If you change this slightly to
$t = $F->Bar();
$t();
then it works.
Upvotes: 0