Sobes.tech
Middle

What is a closure in PHP?

sobes.tech AI

Answer from AI

A function-object with the ability to capture variables from the parent scope in which it was created, even after the parent scope has finished executing.

<?php
// Closure capturing $factor
$multiplyBy = function ($factor) {
    return function ($number) use ($factor) {
        return $number * $factor;
    };
};

$double = $multiplyBy(2);
$triple = $multiplyBy(3);

echo $double(10); // Output: 20
echo $triple(10); // Output: 30

Main features:

  • They are instances of the Closure class.
  • They can inherit variables from the parent scope using the use keyword.
  • Inherited variables are inherited by value unless explicitly specified to inherit by reference (use (&$variable)).
  • They are often used to create anonymous functions that "remember" the context in which they were created.
What is a closure in PHP? — PHP - sobes.tech