简体   繁体   中英

PHP and closures

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.

This has been discussed a lot on SO already (see eg 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.

If you want a one-line solution to replace

$F->Bar()

try this:

call_user_func($F->Bar);

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)() , ie function call operator on any expression, but currently only variables can be "called".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM