PHP Callbacks/Callables

PHPServer Side ProgrammingProgramming

Definition and Usage

Callback is a pseudo-type in PHP. With PHP 5.4, Callable type hint has been introduced, which is similar to Callback. When some object is identified as callable, it means that it can be used as a function that can be called. A callable can be a built-in or user defined function or a method inside any class.

The is_callable() function can be used to verify if the identifier is a callable or not. PHP has call_user_function() that accepts a function's name as a parameter.

Following example shows a built-in function is a callable.

Example

 Live Demo

<?php
var_dump (is_callable("abs"));
?>

Output

This will produce following result −

bool(true)

In following example a user defined function is tested for being callable.

Example

 Live Demo

<?php
function myfunction(){
   echo "Hello World";
}
echo is_callable("myfunction") . "\n";
call_user_func("myfunction")
?>

Output

This will produce following result −

1
Hello World

To pass a object method as a callable, the object itself and its method are passed as two elements in an array

Example

 Live Demo

<?php
class myclass{
   function mymethod(){
      echo "This is a callable" . "\n";
   }
}
$obj=new myclass();
call_user_func(array($obj, "mymethod"));
//array passed in literal form
call_user_func([$obj, "mymethod"]);
?>

Output

This will produce following result −

This is a callable
This is a callable

Static method in a class can also be passed as callable. Instead of object, name of the class should be first element in array parameter

Example

 Live Demo

<?php
class myclass{
   static function mymethod(){
      echo "This is a callable" . "\n";
   }
}
$obj=new myclass();
call_user_func(array("myclass", "mymethod"));
//using scope resolution operator
call_user_func("myclass::mymethod");
?>

Output

This will produce following result −

This is a callable
This is a callable
raja
Published on 19-Sep-2020 17:56:10
Advertisements