The callback in PHP lets you pass functions as arguments and reuse code. It helps you to control how tasks run and simplify logic inside functions.
Table of Content
The callable Keyword in PHP
The callable keyword is a type hint in PHP. It tells PHP that a function or method expects another function as an argument. Then, PHP checks if the value is callable before it runs.
Here is the syntax:
function run(callable $func, $value) {
return $func($value);
}PHP checks whether the argument is callable and runs it when true. It throws a TypeError.
You can use the callable keyword to make a type that checks the strict. It requires a valid callable which can be passed in.
Regular Function as Callable
function double($x) {
return $x * 2;
}
function run(callable $func, $value) {
return $func($value);
}
echo run("double", 5);This example passes double function into the run while callable type. It gives you this result: 10
Anonymous Function as Callable
function apply(callable $func, $value) {
return $func($value);
}
echo apply(function($n) { return $n + 10; }, 15);
This example passes an inline anonymous function into the apply function. The callable runs on the given value and adds ten.
Object Method as Callable
class Math {
public function square($n) {
return $n * $n;
}
}
function compute(callable $func, $value) {
return $func($value);
}
$obj = new Math();
echo compute([$obj, "square"], 6);It uses an object method with callable. So here, PHP just checks the method before it runs and then gives the squared value.
Understand the Callable in PHP to Call a User-Defined Function
A callable is any code piece that PHP can treat as a function. It can be a simple function name, an object method, or a static method. PHP can run it with call_user_func.
Here is the syntax:
call_user_func($callable, $arg1, $arg2);You write it like this to pass any callable. PHP runs the callable and gives back the result.
You can use a callable to pass a function to another function. You can decide later which function to run.
Regular Function
A regular function is a simple function that you define with function. You can pass its name as a callable string.
Here is an example:
function greet_user($name) {
return "Hello " . $name;
}
echo call_user_func("greet_user", "Sam");This runs the greet function through call_user_func and prints the result.
Object Method
An object method is a function inside a class. You can pass it as an array with the object and method name.
class Greeter {
public function say($name) {
return "Hi " . $name;
}
}
$obj = new Greeter();
echo call_user_func([$obj, "say"], "John");This calls the say method of $obj and prints the text.
Static Method
A static method is part of a class that you can call without an object. You can pass it like this ["ClassName", "methodName"].
For example:
class Welcome {
public static function run($name) {
return "Welcome " . $name;
}
}
echo call_user_func(["Welcome", "run"], "Nora");This runs the static method and shows the message.
Do not use callable if you can call the function directly. It adds overhead and makes the code harder to trace.
Understand the Callback in PHP
A callback is a function that you pass into another function so that PHP runs it later. It can be a regular function, an anonymous function, or an object method.
Here is how to use it:
array_map($callback, $array);You can use the callback in array functions, custom functions, and class methods.
Regular Function
function square($x) {
return $x * $x;
}
$result = array_map("square", [1, 2, 3]);
print_r($result);Here is the output:
Array
(
[0] => 1
[1] => 4
[2] => 9
)
This sends square as a callback to array_map and gives squared values.
Anonymous Function
$result = array_map(function($x) { return $x + 5; }, [1, 2, 3]);
print_r($result);This uses an inline function as a callback without a name.
Object Method
class Math {
public function double($x) {
return $x * 2;
}
}
$obj = new Math();
$result = array_map([$obj, "double"], [2, 4, 6]);
print_r($result);The output:
Array
(
[0] => 4
[1] => 8
[2] => 12
)
This uses an object method as a callback inside array_map.
Function Take Callbacks
function runTwice($callback, $value) {
return $callback($callback($value));
}
echo runTwice("sqrt", 16);This calls the callback two times on the given value.
Array Callbacks
$result = array_filter([1, 2, 3, 4], function($x) { return $x % 2 == 0; });
print_r($result);Here is the output:
Array
(
[1] => 2
[3] => 4
)
This uses a callback to filter even numbers in the array.
The Difference Between Callable and Callback in PHP
A callable is anything PHP can call as a function. A callback is a callable that you pass into another function to run it later.
Here is a table that shows you the key differences:
| Aspect | Callable | Callback |
|---|---|---|
| Definition | Any callable unit | Callable passed to another function |
| Use | Direct run with call_user_func | Passed to a host function |
| Form | Function, method, static | Function, method, anonymous, array |
You can use callable when you need a dynamic call with call_user_func and a callback when you want another function to handle calls.
Examples
Pass a Function as Callable:
function upper($text) {
return strtoupper($text);
}
echo call_user_func("upper", "hello php");It sends the upper function to call_user_func and runs the function. It changes the text to uppercase before output.
Callback with Array Filter:
$data = [10, 15, 20, 25];
$result = array_filter($data, function($x) { return $x > 15; });
print_r($result);This example uses a callback with array_filter. It checks each number and keeps only those greater than fifteen in the final result.
Object Method as Callback:
class Text {
public function reverse($str) {
return strrev($str);
}
}
$obj = new Text();
$result = array_map([$obj, "reverse"], ["abc", "xyz"]);
print_r($result);This example shows an object method as a callback. It takes each string in the array and then reverses the letters.
Static Method with Callable:
class MathOp {
public static function cube($n) {
return $n * $n * $n;
}
}
echo call_user_func(["MathOp", "cube"], 4);This example shows a static method as a callable. PHP runs the method directly and calculates the cube of the given number.
Wrapping Up
You learned what callable means and what callback means.
Here is a quick recap:
- Callable is any code PHP can call like a function, method, or static method.
- Callback is a callable that you pass to another function to use it later.
- You saw regular functions and object methods. Also learned the static methods and anonymous functions with examples.
FAQs
What is a callable in PHP with example?
call_user_func.
function hello($name) {
return "Hi " . $name;
}
echo call_user_func("hello", "Sam"); - This code defines a function
hello. - You send the function name as a string to
call_user_func. - PHP runs the function and prints "Hi Sam".
What is the difference between callable and callback in PHP?
- Callable runs directly with
call_user_func. - Callback passes to a function like
array_maporarray_filter.
// Callable
function add($a, $b) {
return $a + $b;
}
echo call_user_func("add", 2, 3);
// Callback
function square($x) {
return $x * $x;
}
print_r(array_map("square", [1, 2, 3])); How does the PHP callable keyword work?
function run(callable $func, $value) {
return $func($value);
}
function double($n) {
return $n * 2;
}
echo run("double", 5); callable $funcmeans only a callable can pass here.- PHP checks the type before execution.
- This makes the function safe and predictable.
When should I avoid using callbacks in PHP?
// Callback way
$result = array_map(function($x) {
return $x + 1;
}, [1, 2, 3]); // Direct loop way
$data = [1, 2, 3];
foreach ($data as &$x) { $x = $x + 1; }
print_r($data); - The callback version uses
array_map. - The loop version runs faster with fewer function calls.
- Use callbacks only when you need flexibility in code.
Similar Reads
The term $_POST is quite familiar territory when one works with forms in PHP. This tutorial talks about what $_POST does, how to use…
If you are working with PHP and need a way to confirm if something is indeed a file, the is_file function will…
The variable scope in PHP refers to the variables, functions, and classes that can be accessed within different parts of…
In PHP, there is this interesting operator known as "exclusive OR," or just XOR. It is somewhat of an underdog…
Before the spread operator, PHP developers had to pass array items to a function using extra steps. They often had…
PHP supports OOP with access modifiers to prevent unintended changes and improve security. In this article, we will cover the…
PHP has great tools to handle external files such as opening, writing, deleting and more else, in this tutorial we…
PHP math may sound like a pretty simple thing, but I assure you it's a set of tools that will…
PHP array_diff_key compares arrays and removes elements that share the same key. It checks only keys and keeps the values…
When you start working with PHP, you’ll soon need access to variables from multiple places in your code. For this,…