0
0
PHPprogramming~5 mins

Why closures matter in PHP

Choose your learning style9 modes available
Introduction

Closures let you create small pieces of code that remember the environment where they were made. This helps you write cleaner and more flexible programs.

When you want to pass a small function as a value to another function.
When you need a function to remember variables from outside its own code.
When you want to create quick, one-time-use functions without naming them.
When you want to keep some data private inside a function.
When you want to delay running some code but keep its context.
Syntax
PHP
<?php
$greet = function($name) {
    return "Hello, $name!";
};
echo $greet('Alice');

A closure is an anonymous function assigned to a variable.

You can call the closure using the variable name like a regular function.

Examples
A simple closure with no parameters.
PHP
<?php
$sayHi = function() {
    return "Hi!";
};
echo $sayHi();
This closure uses use to remember the $message variable from outside.
PHP
<?php
$message = 'Hello';
$greeter = function($name) use ($message) {
    return "$message, $name!";
};
echo $greeter('Bob');
Passing a closure as a callback to filter an array.
PHP
<?php
function filterArray($arr, $callback) {
    $result = [];
    foreach ($arr as $item) {
        if ($callback($item)) {
            $result[] = $item;
        }
    }
    return $result;
}

$numbers = [1, 2, 3, 4, 5];
$even = filterArray($numbers, function($n) {
    return $n % 2 === 0;
});
print_r($even);
Sample Program

This program shows how a closure remembers the $message variable from outside and uses it inside the function.

PHP
<?php
$message = 'Good morning';

$greet = function($name) use ($message) {
    return "$message, $name!";
};

echo $greet('Emma');
OutputSuccess
Important Notes

Closures can capture variables from their surrounding scope using the use keyword.

Without use, closures cannot access outside variables directly.

Closures help keep code organized and avoid global variables.

Summary

Closures are anonymous functions that can remember variables from outside.

They let you write flexible and reusable code blocks.

Closures are useful for callbacks, private data, and cleaner code.