PHP Variable functions

PHPServer Side ProgrammingProgramming

Introduction

If name of a variable has parentheses (with or without parameters in it) in front of it, PHP parser tries to find a function whose name corresponds to value of the variable and executes it. Such a function is called variable function. This feature is useful in implementing callbacks, function tables etc.

Variable functions can not be built eith language constructs such as include, require, echo etc. One can find a workaround though, using function wrappers.

Variable function example

In following example, value of a variable matches with function of name. The function is thus called by putting parentheses in front of variable

Example

 Live Demo

<?php
function hello(){
   echo "Hello World";
}
$var="Hello";
$var();
?>

Output

This will produce following result. −

Hello World

Here is another example of variable function with arguments

Example

 Live Demo

<?php
function add($x, $y){
   echo $x+$y;
}
$var="add";
$var(10,20);
?>

Output

This will produce following result. −

30

In following example, name of function to called is input by user

Example

<?php
function add($x, $y){
   echo $x+$y;
}
function sub($x, $y){
   echo $x-$y;
}
$var=readline("enter name of function: ");
$var(10,20);
?>

Output

This will produce following result. −

enter name of function: add
30

Variable method example

Concept of variable function can be extended to method in a class

Example

<?php
class myclass{
   function welcome($name){
      echo "Welcome $name";
   }
}
$obj=new myclass();
$f="welcome";
$obj->$f("Amar");
?>

Output

This will produce following result. −

Welcome Amar

A static method can be also called by variable method technique

Example

 Live Demo

<?php
class myclass{
   static function welcome($name){
      echo "Welcome $name";
   }
}
$f="welcome";
myclass::$f("Amar");
?>

Output

This will now throw exception as follows −

Welcome Amar
raja
Published on 18-Sep-2020 14:00:58
Advertisements