Current Location: Home> Latest Articles> PHP Function Pointer Tutorial: How to Create and Pass Callback Functions

PHP Function Pointer Tutorial: How to Create and Pass Callback Functions

M66 2025-07-15

What is a PHP Function Pointer?

In PHP, a function pointer is a variable that points to the address of a function, commonly referred to as a callback function. Function pointers allow for dynamic function calls or passing functions, adding flexibility to your code.

Basic Syntax of Function Pointers

The syntax for using function pointers in PHP is as follows:

$functionPointer = 'function_name';

Practical Example

Performing Specific Operations on an Array

You can use function pointers to perform custom operations on an array. For example, the following code demonstrates how to use the usort function to sort an array of numbers in ascending order:

function sortAscending($a, $b) {
    return $a - $b;
}
$numbers = [5, 2, 8, 1, 4];
usort($numbers, 'sortAscending');
print_r($numbers); // Output: [1, 2, 4, 5, 8]

Passing Functions as Parameters

Function pointers can also be passed as parameters to other functions. For instance, the following code shows how to pass an anonymous function as a parameter to array_map:

$strings = ['hello', 'world', 'php'];
$mappedStrings = array_map(function($string) {
    return strtoupper($string);
}, $strings);
print_r($mappedStrings); // Output: [HELLO, WORLD, PHP]

Considerations

  • Function pointers point to the function name, not the function reference.
  • Ensure that the function the pointer refers to has the correct parameters and return values.
  • When using function pointers, make sure the function they point to always exists.