ExpertRefresh

Function / Anonymous  

Related Pages

Definition
Variables
Anonymous
Reference


0.0% 100%
 
 
0 pages 298 questions
1) What is the output of the following code? <?php function func($x, $x=1, $x=2) { return $x; } print func(3);





2) What will the following script output? <?php $a = function($var) { $b = "Hello $var"; return $b; } echo $a('World');







Anonymous functions, also known as closures, allow the creation of functions which have no specified name. <?php preg_match("/-([a-z])/", "hello-world", $match); echo $match[0]; // output -w echo $match[1]; // output w echo preg_replace_callback('/-([a-z])/', function($match) { return strtoupper($match[1]); }, 'hello-world'); // output helloWorld Be aware of the ; after function declaration. Without it, the following code will output a Notice (Parse error syntax) <?php $a = function($var) { $b = "Hello $var"; return $b; }; echo $a('World'); // output Hello World Anonymous functions are useful when using functions that require a callback function like array_filter or array_map do: <?php $data = array(0, 3, 10); $data = array_filter($data, function($x) { return $x%2 == 0; }); // even var_dump($data); /* array (size=2) 0 => int 0 2 => int 10 */ $data = array(0, 3, 10); $data = array_map(function ($x) { return $x*$x; }, $data); // square var_dump($data); /* array (size=3) 0 => int 0 1 => int 9 2 => int 100 */


References