Creating and invoking an anonymous function in a single statement

Viewed 12328

A php closure or anonymous function is used to create function without specifying its name.

Is it possible to call them without assigning to identifier as we do in JavaScript ? e.g.

(function(){
    echo('anonymous function');
})();

What is the correct use of use construct while defining anonymous function and what is the status of anonymous function in public method with accessibility to private properties?

$anon_func = 
function($my_param) use($this->object_property){ //use of $this is erroneous here
    echo('anonymous function');
};
5 Answers

example 1

(new class {
    function __invoke($n) {
        echo "in PHP 7.\n";
    }
})(0);

example 2

(function() { echo "in PHP 7.\n"; })();

example 3

call_user_func(function() { echo "in php> 5.6\n"; });
Related