Request for Comments: Short syntax for anonymous functions


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.

$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!

Passing an anonymous function to a function

The syntax allows for a cleaner way to pass a an anonymous function around.

setFormattingStrategy({$string =>
    return trim(strtolower($string));

Adding variables to the function scope

setFormattingStrategy({$string use $filter =>
    return $filter->trimedAndLowerCase($string));

What is common use cases in other language

Building domain specific languages

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);
function it($testName, callable $test) {
    print("    $testName" . PHP_EOL);
// 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");

Pros and Cons


  • Good for framework development when more expressive callbacks are needed
  • Good for DSLs
  • Removes bloating, unnecessary syntax
  • Other web languages have similar syntax
  • Readable


  • Yet another alias
  • Would take distinctness from block statements
  • Not as searchable through search engines
  • Patch may be difficult to maintain in future


rfc/short-syntax-for-anonymous-function.txt · Last modified: 2017/09/22 13:28 (external edit)