Any normal person would just live without anonymous functions in PHP, they are buggy and non trivial ones are pain to write and read. I’m not sure why I seam to obsess over them.
At the very least, the below code will test unicode in your dev tools
Edit: Of course after I wrote that I discovered that WordPress was ignoring the λ character. A little fix from here and everything is working again.
<?php
// Create an 'anonymous' function without specifying arguments.
// Arguments are considered to be named $a to $z
function λ($body)
{
$args = '';
if(preg_match_all('#(\$[a-z])\b#', $body, $matches, PREG_SET_ORDER) !== 0)
{
$allArgs = array();
foreach($matches as $match)
{
$allArgs[] = $match[1];
}
$allArgs = array_unique($allArgs);
sort($allArgs);
$args = implode(',', $allArgs);
}
// Make sure it's terminated (we don't care about extra trailing ';')
return create_function($args, $body . ';');
}
// Creating
$multiply = λ('return $a * $b');
echo "23 * 65 = " . $multiply(23, 65) . "\n";
// Only $a to $z are reserved
$bSquaredByA = λ('$unused = "Hello"; $b_square = $b * $b; return $b_square * $a');
echo "8 * 6^2 = " . $bSquaredByA(8, 6) . "\n";
// Embedding in strings
$square = λ('return $a * $a');
$numbers = array(2,4,8);
foreach($numbers as $num)
{
echo "$num * $num = {$square($num)}\n";
}
// Note you don't have to use $a for your first argument, and $b for your second. They just
// Need to be in the right order
$print_two_things = λ('echo "Second: " . $y . "\n"; echo "First: " . $d . "\n";');
$print_two_things("Hello", "World!");
// Practical use
$numbers = array(1,1,1,2,2,3,3,3,4,5,5,6,7,8,9);
$above_three = array_filter($numbers, λ('return $x > 3;'));
echo "Numbers above three = " . implode(", ", $above_three) . "\n";
?>