How to work anonymous function in PHP

When reading the documentation for Anonoymous functions in PHP, I come across something special in the syntax.

This statement performs an anonymous function on a single line, but I do not understand why:

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

I understand that the function returns a string data type and an echo, but I'm not sure what delmiters () do around an anonymous function. Can someone explain?

+4
source share
2 answers

Instead of directly passing a value through a method, you can create anonymous functions.

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

Separators () are used as BODMAS in mathematics, where (4 * 2) + 2 will be 10. Tell the compiler that you want to set the closure before executing it.

The long version will be

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

This works with class instances and other options, for example:

(new Object)->method();

( ) , ,

+1

. PHP7 +.

PHP5.3 +

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

, " ", , - .

+2

Source: https://habr.com/ru/post/1656643/


All Articles