Anonymous functions now available from PHP 5.3

Written by . Filed under News, PHP + mySQL. Tagged , , , , , , , , , , , . Bookmark the Permalink. Post a Comment. Leave a Trackback URL.

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

Example:

1
2
3
4
$myName = function($name)
{
    echo "My name is $name";
};

Or you can use it as callback like javascript

1
2
3
4
5
6
7
8
9
10
11
12
$arr = array(
    "first_name" => "Garry",
    "last_name" => "Lachman",
    "age" => "27"
);

$callback_function = function ($field, $field_value)
{
    echo "$field = $field_value";
};
       
array_walk($arr, $callback_function);

Using variables out function scope

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$prefix = "*)";

$arr = array(
    "first_name" => "Garry",
    "last_name" => "Lachman",
    "age" => "27"
);

$callback_function = function ($field, $field_value) use ($prefix)
{
    echo "$prefix $field = $field_value";
};
       
array_walk($arr, $callback_function);

Have fun boys & girls :)

Post a Comment

Your email is never published nor shared.

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*