Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Callback Functions

Callback Functions

A callback function, or simply “callback,” is a function passed as an argument to another function.

Any existing function can serve as a callback. To use a function as a callback, pass its name as a string argument to another function.

Example

Pass a callback to PHP’s array_map() function to compute the length of each string in an array.

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

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

Callbacks in User Defined Functions

User-defined functions and methods can also accept callback functions as arguments. To invoke a callback function within a user-defined function or method, use parentheses with the variable and pass arguments just like with regular functions.

Example

Execute a callback within a user-defined function:

<?php
function exclaim($str) {
  return $str . “! “;
}

function ask($str) {
  return $str . “? “;
}

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

// Pass “exclaim” and “ask” as callback functions to printFormatted()
printFormatted(“Hello world”“exclaim”);
printFormatted(“Hello world”“ask”);
?>