The PHP callable or callback refers to a construct that can be called like a function, including regular functions, object methods, and static methods, allowing for flexibility in how code is executed when calling the main function.

In PHP, the terms “callable” and “callback” are related concepts but have slightly different meanings. So, before getting started, let’s take a look at the differences between them.

The Difference Between Callable and Callback

A callable in PHP refers to anything that can be called as a function. Additionally, it’s a type hint used in function signatures or other contexts to indicate that a variable or parameter should be a valid callable entity.

Moreover, callables can take different forms, including regular functions, object methods, static methods, closures, or even certain types of arrays.

To illustrate, here’s a simple example of the PHP callable:

<?php

function myFunction() {
    echo "Hello, world!";
}

$callable = 'myFunction'; // callable variable
$callable(); // calling the function using the variable

Whilst, the callback specifically refers to a function that is passed as an argument to another function and is intended to be executed at a later point in the program.

Callbacks are often used in scenarios such as event handling, asynchronous operations, or custom sorting functions.

To illustrate, here is an example below shows you how to use the callback:

<?php

function performOperation($callback) {
    // ... do some work ...
    $result = $callback(); // calling the callback function
    // ... do more work ...
    return $result;
}

function myCallback() {
    return "Callback executed!";
}

$result = performOperation('myCallback');
echo $result; // Output: Callback executed!

Furthermore, let’s delve into more details about PHP callable.

Understanding the PHP Callable

As I mentioned before, the callable in PHP refers to any function, method, or class that can be invoked as if it were a function. This includes standard functions, closures, object methods, and static methods.

In other words, the term “callable” is an umbrella that covers a broad spectrum of entities, enabling developers to write code that seamlessly adapts to different scenarios.

Let’s see some examples:

At its core, a callable in PHP can be a regular function. This encompasses built-in functions like strlen() or user-defined functions created with the function keyword. Moreover, developers can use this fundamental aspect of PHP to encapsulate functionality into modular units that they can easily swap in and out as needed. For example:-

<?php

$regularFunction = function ($name) {
    return "Hello, $name!";
};

$callableResult = $regularFunction('John');
echo $callableResult; // Output: Hello, John!

PHP callable extend beyond regular functions to include methods within objects. This proves particularly useful in object-oriented programming (OOP), where developers can treat an object’s methods as standalone entities that they can pass around and execute dynamically.

Here is an example:-

<?php 

class Greeting {
    public function sayHello($name) {
        return "Hello, $name!";
    }
}

$obj = new Greeting();
$objectMethod = [$obj, 'sayHello'];

$callableResult = call_user_func($objectMethod, 'Jane');
echo $callableResult; // Output: Hello, Jane!

Static methods, which are not tied to a specific instance of a class, are also callable in PHP. This provides a level of flexibility when dealing with class-level functionality without requiring an object instantiation.

To illustrate, check the below example:-

<?php

class MathOperations {
    public static function add($a, $b) {
        return $a + $b;
    }
}

$staticMethod = ['MathOperations', 'add'];

$callableResult = call_user_func($staticMethod, 5, 3);
echo $callableResult; // Output: 8

Anyway, let’s move to the last part of this tutorial, which is PHP callback.

Understanding the PHP Callback

In PHP, the PHP callback refers to a mechanism that allows you to dynamically execute a function or method. Additionally, callbacks are powerful tools for creating flexible and extensible code, enabling you to pass functions or methods as parameters to other functions, classes, or methods. This concept is closely tied to the idea of callable in PHP.

Here are examples showcasing various types of PHP callbacks:

A callback can be a regular function, either built-in or user-defined. This is the simplest form of a callback, where a function is referenced by its name.

Here is an example:-

<?php
function myFunction($param) {
    echo "Callback executed with parameter: $param";
}

$callback = 'myFunction';
call_user_func($callback, 'Hello World');

Anonymous functions, also known as closures, can be used as callbacks. These functions are defined on-the-fly without a specific name and are useful for short, one-off operations. For an example:-

<?php
$callback = function ($param) {
    echo "Callback executed with parameter: $param";
};

call_user_func($callback, 'Hello World');

Callbacks can reference methods within objects. This is particularly useful in an object-oriented context, allowing for dynamic execution of methods.

The following code shows you an example:-

<?php
class MyClass {
    public function myMethod($param) {
        echo "Callback executed with parameter: $param";
    }
}

$obj = new MyClass();
$callback = [$obj, 'myMethod'];
call_user_func($callback, 'Hello World');

Let’s explore additional patterns for real functions already defined by the user for PHP callbacks:-

Some PHP functions accept callbacks as parameters, allowing you to customize their behavior dynamically.

<?php
function processCallback($callback, $param) {
    call_user_func($callback, $param);
}

processCallback('myFunction', 'Hello World');

Arrays in PHP provide numerous functions that accept callbacks, such as array_map, array_filter, and array_reduce. Additionally, these functions allow you to manipulate arrays based on the provided callback.

<?php
$numbers = [1, 2, 3, 4, 5];

// Square each number using a callback
$squaredNumbers = array_map(function ($n) {
    return $n * $n;
}, $numbers);

print_r($squaredNumbers);

Let’s wrap up.

Wrapping Up

In summary, callable is a broader term that encompasses anything that can be called as a function, while a callback specifically refers to a function that is passed as an argument to another function for later execution.

The term “callback” is often used in the context of functions passed as parameters, but the term “callable” is more general and includes a wider range of callable entities.

We refer to the PHP manual as a resource for this tutorial. For additional PHP tutorials, visit here.