views:

123

answers:

2

Hi,

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. :)

+1  A: 

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) );
  }
}

?>
Seb
oh really, never looked at that. I thought that you can`t programm in a functional way in php. And just see anonym functions in the release notes :) So the new feature is only another way to define anonym functions?
evildead
create_function() is similiar to eval() isn't it ? The new way described by Ólafur Waage looks much better.
alex
eval() lets you "run" any piece of PHP code (i.e.eval("print (1 + 9);"), whereas create_function() creates a function and returns it to be used later, as the example I wrote above.
Seb
+3  A: 

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.

Wikipedia quote:

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

Ólafur Waage