PHP Callable & Callback: Pass a Function to Another

php callable and callback in php

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.

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:

AspectCallableCallback
DefinitionAny callable unitCallable passed to another function
UseDirect run with call_user_funcPassed to a host function
FormFunction, method, staticFunction, 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?

A callable in PHP is anything that PHP can treat as a function. It can be a function name, an object method, or a static method. You can run it with 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?

A callable is any function, method, or static function that PHP can run. A callback is a callable that you pass into another function for later execution.
  1. Callable runs directly with call_user_func.
  2. Callback passes to a function like array_map or array_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?

The callable keyword is a type hint. It tells PHP that a parameter must be a callable function or method.
function run(callable $func, $value) { 
   return $func($value);
} 

function double($n) {
   return $n * 2;
} 

echo run("double", 5);
  • callable $func means 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?

You should avoid callbacks if a simple loop or direct call works faster. Too many callbacks reduce speed and make code harder to follow.
// 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

PHP $_POST: Handling Form Data in PHP

The term $_POST is quite familiar territory when one works with forms in PHP. This tutorial talks about what $_POST does, how to use…

PHP is_file Function: Check if a File Exists

If you are working with PHP and need a way to confirm if something is indeed a file, the is_file function will…

PHP Variable Scope: Local, Global & Static

The variable scope in PHP refers to the variables, functions, and classes that can be accessed within different parts of…

Understanding the PHP Exclusive OR (XOR) Operator

In PHP, there is this interesting operator known as "exclusive OR," or just XOR. It is somewhat of an underdog…

PHP Spread Operator: Understand How (…) Syntax Works

Before the spread operator, PHP developers had to pass array items to a function using extra steps. They often had…

PHP Access Modifiers: How Public, Private & Protected Work

PHP supports OOP with access modifiers to prevent unintended changes and improve security. In this article, we will cover the…

PHP fopen: Understanding fopen Modes

PHP has great tools to handle external files such as opening, writing, deleting and more else, in this tutorial we…

PHP Math: Essential Functions with Examples

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 Function: How it Works with Examples

PHP array_diff_key compares arrays and removes elements that share the same key. It checks only keys and keeps the values…

PHP $GLOBALS: Access Global Variables with Examples

When you start working with PHP, you’ll soon need access to variables from multiple places in your code. For this,…

Previous Article

PHP Named Arguments vs. Positional Arguments

Next Article

PHP Variable Scope: Local, Global & Static

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.