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.
The syntax for using function pointers in PHP is as follows:
$functionPointer = 'function_name';
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]
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]