Sobes.tech
Junior

What are lambda functions and anonymous functions? Tell about them.

sobes.tech AI

Answer from AI

Lambda functions and anonymous functions in PHP are essentially the same: functions without a name.

They can be assigned to a variable and passed as arguments to other functions.

Main differences from regular functions:

  • No name: Defined with the function keyword.
  • Can be assigned to a variable: The variable becomes callable.
  • Can be passed as a callback: Used in higher-order functions (array_map, array_filter, etc.).
  • Can "capture" variables from the parent scope: Using the use keyword.

Example of assigning to a variable:

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

$greet('World');

Example of using as a callback:

<?php
$numbers = [1, 2, 3, 4, 5];

$squaredNumbers = array_map(function($n) {
    return $n * $n;
}, $numbers);

print_r($squaredNumbers);

Example of "capturing" variables:

<?php
$message = 'Hello';

$greet = function($name) use ($message) {
    printf("%s, %s!\n", $message, $name);
};

$greet('World');

The use keyword allows an anonymous function to access variables defined in the scope where it was created. Variables passed into use are copied by value unless a reference (&) is specified.

They are widely used for creating short, one-time functions, often inside other functions or methods to perform specific tasks.

What are lambda functions and anonymous functions… - sobes.tech