Sobes.tech
Junior — Middle

Can you explain what a closure is and how it works in PHP?

sobes.tech AI

Answer from AI

In PHP, a closure is an anonymous function that can capture variables from its surrounding scope and use them inside itself even after the outer function has finished executing. This allows creating functions with preserved state.

Example:

function counter() {
    $count = 0;
    return function() use (&$count) {
        $count++;
        return $count;
    };
}

$countFunc = counter();
echo $countFunc(); // 1
echo $countFunc(); // 2

Here, the anonymous function captures the variable $count by reference and retains its value between calls.

Can you explain what a closure is and how it works in… - sobes.tech