Sobes.tech
Junior — Middle

How is an anonymous function that uses external parameters implemented?

sobes.tech AI

Answer from AI

In PHP, an anonymous function (closure) can use external variables with the use keyword. This allows passing values from the outer scope into the function.

Example:

$factor = 10;
$multiply = function($number) use ($factor) {
    return $number * $factor;
};

echo $multiply(5); // Outputs 50

Here, the variable $factor from the outer scope is passed into the anonymous function via use. Without this keyword, the function would not have access to $factor.