Saturday, October 25, 2025
HomeLanguagesHow to call PHP function from string stored in a Variable

How to call PHP function from string stored in a Variable

Given the names of some user-defined functions stored as strings in variables. The task is to call the functions using the names stored in the variables.

Example:




<?php
  
// Function without argument 
function func() {
    echo "geek";
}
  
// Function with argument
function fun($msg) {
    echo $msg;
}
  
// Call func and fun using $var and $var1
$var = "func";
$var1 = "fun";     
?>


There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used.

Program:




<?php
  
// Function without argument 
function func() {
    echo "hello ";
}
  
// Function with argument
function fun($msg) {
    echo $msg." ";
}
      
$var = "func";
$var1 = "fun"
      
// 1st method by using variable name
$var();
$var1("geek");
  
echo "\n";
  
// 2nd method by using php inbuilt
// function call_user_func()
call_user_func($var);
call_user_func($var1, "fun_function"); 
  
?>


Output:

hello geek 
hello fun_function

Another Method: Using eval() Function: The eval() function is an inbuilt function in PHP which is used to evaluate string as PHP code.
Note: This method is contributed by Vineet Joshi.
Syntax:

eval( $code )

Parameters: This function accepts single parameter code which is used to hold the PHP code as a string.

Example:




<?php
  
// Function without argument 
function writeMessage() {
    echo "Welcome to neveropen!";
}
  
// Declare variable and store
// function name    
$functionName = "writeMessage();";
  
// Function call using eval
eval($functionName);
?>


Output:

Welcome to neveropen!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS