
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
PHP Callbacks/Callables
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
<?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
<?php function myfunction(){ echo "Hello World"; } echo is_callable("myfunction") . "
"; 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
<?php class myclass{ function mymethod(){ echo "This is a callable" . "
"; } } $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
<?php class myclass{ static function mymethod(){ echo "This is a callable" . "
"; } } $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
- Related Articles
- JavaScript Callbacks
- Callbacks in C
- Promises Callbacks And Async/Await
- Use of Callbacks in Layered Architecture
- What are the arguments to Tkinter variable trace method callbacks?
- How to use API inside callbacks using jQuery DataTables plugin ?
- How can Forgotten timers or callbacks cause memory leaks in JavaScript?
- PHP php://
- Upload file with php to another php server
- PHP Generators.
- PHP Overloading
- PHP Traits
- PHP $_GET
- PHP $GLOBALS
- PHP $_SERVER
