← Back to PHP Course | Chapter 5: Functions | Lesson 7 of 10

PHP Anonymous Functions

An anonymous function is a small helper with no name, like a quick note you hand to someone instead of publishing it in a book. You can store it in a variable or pass it around.
Syntax
php
$closure = function ($parameter) use ($outer_variable) {
    return $parameter;
};

$closure($argument);

What is an Anonymous Function?

An anonymous function (a closure) is defined without ever being given a name of its own — instead of calling it by name later, you typically assign it directly to a variable or hand it straight to another function as an argument.

Example: What is an Anonymous Function?

php
<?php
$greet = function ($name) {
    // Print "Hello, $name!" to the output
    echo "Hello, $name!";
};
$greet("Alice");
?>

Using Closures as Callbacks

Built-in array functions like array_filter() and usort() expect a callback to tell them exactly how to filter or compare elements.

An anonymous function defined right at the call site is a natural fit here, since that logic is usually one-off and doesn't need a name of its own elsewhere in the codebase.

Example: Using Closures as Callbacks

php
<?php
// Declare `$numbers` as an array: `[1, 2, 3, 4, 5]`
$numbers = [1, 2, 3, 4, 5];
$even = array_filter($numbers, function ($n) {
    // Return `$n % 2 === 0` from this function
    return $n % 2 === 0;
});
// Print a human-readable dump of `$even`
print_r($even);
?>

The 'use' Keyword

The use keyword lets a closure pull in variables from the scope it was defined in — without it, the closure has no access to anything outside its own parameter list, even variables that were clearly visible right where the closure was written.

Example: The 'use' Keyword

php
<?php
// Declare `$tax`, set to `0.1`
$tax = 0.1;
$addTax = function ($price) use ($tax) {
    // Return `$price + ($price * $tax)` from this function
    return $price + ($price * $tax);
};
// Print `$addTax(100)` to the output
echo $addTax(100);
?>

Type Hinting Callables

Declaring a parameter's type as callable (or specifically Closure) documents that a function expects to receive something it can invoke, and lets PHP enforce that at the call site rather than only discovering the mistake when the function tries to call a non-callable value.

Example: Type Hinting Callables

php
<?php
// Define the function `apply` taking `callable $fn`, `$value`
function apply(callable $fn, $value) {
    // Return `$fn($value)` from this function
    return $fn($value);
}
// Print `apply(function ($x) { return $x * 2; }, 5)` to the output
echo apply(function ($x) { return $x * 2; }, 5);
?>

Closures and $this

A closure defined inside a class method automatically has access to $this, referring to the same object instance the enclosing method belongs to — letting the closure read or modify that object's properties and call its other methods just as the surrounding method could.

Example: Closures and $this

php
<?php
// Define the class `Counter`
class Counter {
    // Declare the private property `$count`, set to `0`
    private $count = 0;
    // Define the function `makeIncrementer` with no parameters
    function makeIncrementer() {
        // Return `function () {` from this function
        return function () {
            $this->count++;
            // Return `$this->count` from this function
            return $this->count;
        };
    }
}
// Create a new `Counter` instance, stored in `$counter`
$counter = new Counter();
// Declare `$increment`, set to `$counter->makeIncrementer()`
$increment = $counter->makeIncrementer();
// Print `$increment()` to the output
echo $increment();
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting a closure to see outer variables automatically, when they must be imported with use ($var).
  2. Expecting use ($count) to update the outer variable, when it captures a copy; use use (&$count) for a reference.
  3. Forgetting the semicolon after an anonymous function assigned to a variable, which causes a parse error.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.