Skip to main content

PHP Callback Functions

By SamK
0
0 recommends
Category(s)
Topic(s)

A callback is a function that is passed as an argument to another function. To utilize a function as a callback, you simply pass a string containing the name of the function as an argument to the other function.

Any defined function can serve as a callback.  

In the below example, we are using a callback function example_callback with PHP's array_map() function to fetch items from an array. 

<?php

// Array of color names
$colors = ["red", "blue", "green", "yellow"];

function example_callback($item) {
    return $item;
}

// Apply array_map to get the items
$items = array_map(example_callback, $colors);

// Print the resulting array
print_r($items);

/*
Output:
Array ( [0] => red [1] => blue [2] => green [3] => yellow ) 
*/
?>

Beginning with version 7, PHP allows the use of anonymous functions as callback functions.

Example:

<?php

// Array of animal names
$animals = ["lion", "elephant", "giraffe", "kangaroo"];

// Use an anonymous function to fetch each animal name
$names = array_map(function($item) {return $item;}, $animals);

// Print the resulting array with animal names
print_r($names);

/*
Output:
Array ( [0] => lion [1] => elephant [2] => giraffe [3] => kangaroo ) 
*/
?>

Callbacks in User Defined Functions

User-defined functions and methods can also accept callback functions as arguments, just like regular function arguments.

Example:

<?php

function salute() {
    return "Hello";
}

function name() {
  return "Sami";
};

function greeting($salute,$name) {
  echo $salute() . ' ' . $name() . '!';
}

greeting(salute,name);

/*
Output:
Hello Sami!
*/
?>

Questions & Answers