16 October 2012 · 2 min read
Short Syntax for Closures
- php
- rfc
- functional-programming
Request for Comments: Short Syntax for Closures
- Version: 0.1
- Date: 2012-10-16
- Author: Marcello Duarte
<marcello at inviqa.com> - Status: In Draft
- Patch: Help me if you are an internal developer
Introduction
In some cases it is necessary that you have to pass function parameters as an closure. If your library receives closures, and alternatively closures within closures, 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
A closure 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 NorrisPassing a closure to a function
The syntax allows for a cleaner way to pass a closure around.
trimAndLower($elem -> {
return trim(strtolower($elem));
});What is common use cases in other language
Building domain specific languages
Some languages like Groovy and Ruby allows you to move the closure outside of the list of arguments, if the closure is the last argument of the function call, creating a interesting side effect.
<?php
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");
}
}Pros / 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