In some cases it is necessary that you have to pass an anonymous function to a function/method as a parameter. If your library receives uses an anonymous function, and alternatively nested anonymous functions, having the function keyword makes the code very long and unecessary unreadable. If you take a look at other languages (Ruby, Python, Groovy, Coffescript) there is a short syntax for closure using the language state block container. Maybe PHP should adopt this behaviour to make code more readable and maintainable.
An anonymous function in php could be expressed by a typical statement block, surrounded by curly brackets.
<?php $sayHi = { echo "hi"; }; $sayHi(); // prints: hi $sayHello = { $name => echo "hello, $name"; }; $sayHello("Chuck Norris"); // prints: hello, Chuck Norris $sayHello = { $name, $mood => echo "hello, $name. It's $mood day!"; }; $sayHello("Chuck Norris", "wonderful"); // prints: hello, Chuck Norris. It's a wonderful day!
The syntax allows for a cleaner way to pass a an anonymous function around.
<?php setFormattingStrategy({$string => return trim(strtolower($string)); });
Some languages like Groovy and Ruby allows you to move the anonymous function outside of the list of arguments if it is the last argument of the function call, creating a interesting side effect.
function describe($testedClass, callable $tests) { print ("$testedClass" . PHP_EOL); $tests(); } function it($testName, callable $test) { print(" $test" . PHP_EOL); $test(); } // because the last argument is a callable we can now: describe ("BankAccount") { it ("starts with a zero amount") { $amount = (new BankAccount())->getAmount(); if ($amount !== 0) throw new Failure("Expected 0, got $amount"); } }