What is an anonymous PHP function?

What is an anonymous function in PHP? Could you give me a simple example?

+3
source share
2 answers

PHP.net has a page describing Anonymous Functions and on Wikipedia you can read Anonymous Functions in general.

Anonymous functions can be used to contain functionality that does not need to be named and, possibly, for short-term use. Some well-known examples include closure.

Example from PHP.net

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>

PHP 4.0.1 to 5.3

$foo = create_function('$x', 'return $x*$x;');
$bar = create_function("\$x", "return \$x*\$x;");
echo $foo(10);

PHP 5.3

$x = 3;
$func = function($z) { return $z *= 2; };
echo $func($x); // prints 6

PHP 5.3 supports closure, but variables must be explicitly specified

$x = 3;
$func = function() use(&$x) { $x *= 2; };
$func();
echo $x; // prints 6

Examples taken from Wikipedia and php.net

+15
source

Google :

http://php.net/manual/de/functions.anonymous.php

echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld

, ( ), " ". , , , .

function foo($match) {
 return strtoupper($match[1]);
} 
+1

Source: https://habr.com/ru/post/1764447/


All Articles