What is a closure

A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope. In other words, a closure allows a function to "remember" the environment in which it was created, capturing variables from its outer function.

Closures are commonly used to create private variables or to maintain a state in asynchronous programming.

<?php function outerFunction($outerVariable) { return function($innerVariable) use ($outerVariable) { return $outerVariable + $innerVariable; }; } $closure = outerFunction(5); echo $closure(10); // Outputs: 15 ?>

Closure Lexical Scope PHP Nested Functions Function Scope