Closures let you create small pieces of code that you can pass around and run later. Using them as callbacks means you can tell a function what to do at a certain time.
0
0
Closures as callbacks in PHP
Introduction
When you want to run a small task after another function finishes.
When you need to customize how a function behaves without changing its code.
When you want to keep your code clean by writing short functions inside other functions.
When you want to handle events like button clicks or data processing steps.
When you want to pass a piece of code as an argument to another function.
Syntax
PHP
<?php function exampleFunction(callable $callback) { // Do something $callback(); } exampleFunction(function() { echo "Hello from closure callback!"; }); ?>
A closure is an anonymous function you can create without a name.
Callbacks are functions passed as arguments to other functions to be called later.
Examples
This doubles each number in the array using a closure as a callback.
PHP
<?php // Simple closure as callback array_map(function($n) { return $n * 2; }, [1, 2, 3]); ?>
This multiplies each number by 3 using a closure that accesses an outside variable.
PHP
<?php // Closure with use keyword to access outside variable $multiplier = 3; array_map(function($n) use ($multiplier) { return $n * $multiplier; }, [1, 2, 3]); ?>
This calls the closure with a name to print a greeting.
PHP
<?php // Passing closure as callback to a custom function function greet(callable $callback) { $callback("Alice"); } greet(function($name) { echo "Hello, $name!"; }); ?>
Sample Program
This program uses a closure as a callback to double each number in the list and print it.
PHP
<?php function processNumbers(array $numbers, callable $callback) { foreach ($numbers as $number) { echo $callback($number) . "\n"; } } // Closure doubles the number processNumbers([1, 2, 3], function($n) { return $n * 2; }); ?>
OutputSuccess
Important Notes
Closures can capture variables from outside their scope using the use keyword.
Callbacks must be callable, which means they can be a closure, a named function, or an array with object and method.
Using closures as callbacks helps keep code short and focused.
Summary
Closures are anonymous functions you can pass as callbacks.
Callbacks let you customize behavior by passing code to other functions.
Closures can access outside variables with use.