has anybody tried out the new 5.3.0 RC1 php release and played a bit with anonymous functions?
I would like to know if you can use it like python for functional programming.
E.g., can you do something like:
def sinus(x):
if x<=0.1:
return x
else:
return (lambda x: 3*x-4*x*x*x)(sinus(x/3))
print sinus(172.0)
Or better, can you do all the cool stuff like in python or lisp? Are there any limits? Unfortunately I don´t have a better example in mind. :)
The new anonymous functions in PHP 5.3 are very useful in existing callback functions. As this example shows.
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
It's still a trick, since PHP 5.3 impliments a Closure class that makes a class instance invokable.
PHP 5.3 mimics anonymous functions but it does not support true anonymous functions because PHP functions are still not first-class functions.
You can read more about the Closures in this PHP RFC
Since PHP 4 you can use the function create_function to do what you want.
In your example:
<?php
function sinus($x){
if($x < 0.1) {
return $x;
} else {
$func = create_function('$x', 'return 3*$x-4*$x*$x*$x');
return $func( sinus($x/3) );
}
}
?>