PHP Callback Functions


Callback Functions

A callback function is a function that passes as an argument into another function (commonly referred to as "callback").

Callback function Any existing function can be used. In order to use a function as a callback feature, use a string that contains another function's name :

Example 1 :- To calculate each string in a table, pass a callback to the PHP array_map() method :

<?php
function my_callback($item) {
  return strlen($item);
}

$strings = ["apple", "orange", "banana", "coconut"];
$lengths = array_map("my_callback", $strings);
print_r($lengths);
?>

Output :-

Array
(
[0] => 5
[1] => 6
[2] => 6
[3] => 7
)

Example 2 :- As a callback to PHP's array_map() function, use an anonymous function:

<?php
$strings = ["apple", "orange", "banana", "coconut"];
$lengths = array_map( function($item) { return strlen($item); } , $strings);
print_r($lengths);
?>

Output :-

Array
(
[0] => 5
[1] => 6
[2] => 6
[3] => 7
)

You can also search for these topics, callback function in php, php callback function type, use of php callback function, php callback function with parameters, php callback function example, php callback types, php callback function () use variable, php callback function with arguments, php callback function not found, php callback function pass parameter.

Callbacks in User Defined Functions

Callback functions can also be passed as arguments to user-defined functions and procedures. Call callback functions inside a user-defined function or method by enclosing the variable in parentheses and passing arguments as you would with regular functions :

Example :- Call a user-defined function with a callback :

<?php
function print1($str) {
  return $str . "! <br />";
}

function print2($str) {
  return $str . "? <br />";
}

function myPrint($str, $format) {
  // Calling the $format callback function
  echo $format($str);
}

// Pass "print1" and "print2" as callback functions to "myPrint".

myPrint("Hello world", "print1");
myPrint("Hello world", "print2");
?>

Output :-

Hello world!
Hello world?

You can also search for these topics, php callbacks in user defined functions, php user defined function i=using call backs, Example for Callbacks in User Defined Functions, php callbacks in user defined function passing arguments.