Question

When a method returns a function, it can be called like so:

class AClass {
    public function getFnc() {
        $f = function() {
            echo "hello from a function";
        };
        return $f;
    }
}

On the calling side we can do:

$c = new AClass();
$f = $c->getFnc();
$f(); 

The output is hello from a function as excpected.

Writing the call inline doesn't compile:

$c->getFnc()();

How can this be written inline(ish) possibly with some casting? I am looking for an elegant way from the caller point of view.

In maths, stuff is evaluated in situ:

(3 + 2)(5 + 1)
(5)(6)
30

instead of introducing a unnecessary variable f1:

f1 = (3 + 2)
f1(5 + 1)

...

Was it helpful?

Solution

Your function can be treated as a callback function so call_user_func() will work to invoke the returned function. You can call the function like so...

http://be2.php.net/function.call-user-func

class AClass {
    public function getFnc() {
        $f = function() {
            echo "hello from a function";
        };
        return $f;
    }
}

$c = new AClass();
call_user_func($c->getFnc());

OTHER TIPS

Take a look at this and be sure about the version of your PHP : Anonymous functions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top