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

PHP Anonymous Functions

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) {
    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
$numbers = [1, 2, 3, 4, 5];
$even = array_filter($numbers, function ($n) {
    return $n % 2 === 0;
});
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
$tax = 0.1;
$addTax = function ($price) use ($tax) {
    return $price + ($price * $tax);
};
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
function apply(callable $fn, $value) {
    return $fn($value);
}
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
class Counter {
    private $count = 0;
    function makeIncrementer() {
        return function () {
            $this->count++;
            return $this->count;
        };
    }
}
$counter = new Counter();
$increment = $counter->makeIncrementer();
echo $increment();
?>

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.