iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Callbacks

A callback is a function you pass to another function as an argument. PHP accepts strings, arrays, closures, arrow functions, and first-class callable syntax (8.1+).

Callable forms

FormExample
Function name as string'strtoupper'
Static method as string'MyClass::staticMethod'
Instance method as array[$obj, 'method']
Static method as array['MyClass', 'staticMethod']
Closurefunction ($x) { return $x * 2; }
Arrow functionfn($x) => $x * 2
First-class callable (8.1+)strtoupper(...) or $obj->method(...)

Callback-taking functions

PHP
$nums = [1, 2, 3, 4];

array_map('abs', [-1, -2, -3]);                       // string name
array_map(fn($n) => $n * 2, $nums);                    // arrow
array_filter($nums, fn($n) => $n % 2 === 0);
array_reduce($nums, fn($c, $n) => $c + $n, 0);

usort($users, fn($a, $b) => $a->age <=> $b->age);

Variadic callback

PHP
function pipeline($value, callable ...$steps) {
    foreach ($steps as $step) {
        $value = $step($value);
    }
    return $value;
}

echo pipeline('  Ada  ',
    'trim',
    'strtoupper',
    fn($s) => "Hi, $s!",
);

Type-hint callables

PHP
function each(iterable $items, callable $fn): void {
    foreach ($items as $i) $fn($i);
}

For stricter typing, declare with the Closure class or use callable.

Tip: First-class callable syntax (strtoupper(...)) is the cleanest way to pass a function. Modern static analysers understand it perfectly.

Example

Example
<?php
$nums = [1, 2, 3, 4];
print_r(array_map(fn($n) => $n * 2, $nums));
print_r(array_filter($nums, fn($n) => $n % 2 === 0));
echo array_reduce($nums, fn($c, $n) => $c + $n, 0);
Try it Yourself »

Exercise

First-class callable syntax marker.

$shout = strtoupper ;

Test yourself

Q1. First-class callable syntax is…
Q2. Type-hint a callback with…
Q3. Instance method as array callable is…

Discussion

Loading…