MaximPro
MaximPro

Reputation: 542

How to work anonymous function in PHP

Afted reading the documentation on Anonoymous functions in PHP I come across something particular to syntax.

This statement executes the anonymous function in one line but I do not understand why:

echo (function () {
     return 'hi';
})();

I understand that the function is returning a string data type and echo'ing it but I am unsure to what the () delmiters around the anonymous function are doing. Can anyone explain?

Upvotes: 4

Views: 92

Answers (2)

Jaquarh
Jaquarh

Reputation: 6693

Rather than directly passing a value through to a method you can create anonymous functions.

$example = array(1,2,3);
(function () use ($example) { return $example[0] -1; })();

The () delimiters are used like BODMAS in maths where (4*2) + 2 would be 10. Your telling the compiler you want to set the closure before executing it.

The long version would be

$closure = function () { ....
$closure();

This works with class instances and other variations also like:

(new Object)->method();

(do this first) do this after you get the result of what's done first

Upvotes: 1

Georgy Ivanov
Georgy Ivanov

Reputation: 1579

This is the way to define and invoke the function immediately. This is supported by PHP7+ only though.

An alternative for PHP5.3+ would be

call_user_func(function() {
    echo "Hi";
});

So, if you want to define a function on-the-fly, so to speak, and use it immediately - this is the way to go.

Upvotes: 2

Related Questions