rfc:short-syntax-for-anonymous-function

Request for Comments: Short syntax for anonymous functions

Introduction

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.

Syntax

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!

Passing an anonymous function to a function

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

<?php
 
setFormattingStrategy({$string =>
    return trim(strtolower($string));
});

Adding variables to the function scope

<?php
 
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);
    $tests();
}
 
function it($testName, callable $test) {
    print("    $testName" . 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");
    }
}

Pros and Cons

Pros

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

Cons

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

Changelog

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