phpfunctional-programminginlineanonymous-function

Inline execution of an anonymous function returned by a method: $obj->method()()


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)

...


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...

    https://www.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());