Anonymous

 
/**
 * An anonymous function is a function without a name.
 * There are also called closures or lamba functions.
 * Be aware of the ; after function declaration.
 */

$greet = function($name) {
    return "Hello, $name!";
};

echo $greet('Alice');  // Hello, Alice!

Import variables

 
/**
 * Anonymous function can inherit variables from the parent scope, 
 * using the keyword 'use'.
 */

$message = "Welcome";

$greet = function($name) use ($message) {
    return "$message, $name!";
};

echo $greet("Alice");  // Welcome, Alice!

Callbacks

 
/**
 * Closure are useful when using callbacks.
 * They're ofthen used in function like array_map, array_filter.
 */ 

$numbers = [1, 2, 3];

$squares = array_map(function($n) {
    return $n * $n;
}, $numbers);
print_r($squares);  // 1, 4, 9


$evens = array_filter($numbers, function($n) {
    return $n % 2 == 0;
});
print_r($evens);  // 2

Arrow functions

 
/**
 * Arrow functions provide a shorter syntax for one-line anonymous functions.
 * Arrow functions automatically inherit variables from the parent scope.
 */

$numbers = [1, 2, 3];

$squares = array_map(fn($x) => $x * $x, $numbers);
print_r($squares);  // 1, 4, 9

$evens = array_filter($numbers, fn($x) => $x % 2 == 0);
print_r($evens);  // 2






Questions and answers:
Clink on Option to Answer




1. What are anonymous (or closures)?

  • a) Functions without a name
  • b) Functions without body

2. Correct definition for closure:

  • a) $f = function($x) {};
  • b) $f = function($x) {}

3. How do you define closures inside callback functions?

  • a) function($x) => $x + 1
  • b) fn($x) => $x + 1


References: