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"); ?> |
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 GeeksforGeeks!"; } // Declare variable and store // function name $functionName = "writeMessage();"; // Function call using eval eval($functionName); ?> |
Welcome to GeeksforGeeks!
Recommended Posts:
- How to call function from it name stored in a string using JavaScript?
- How to call a function that return another function in JavaScript ?
- JavaScript | Function Call
- How to call PHP function on the click of a Button ?
- How to get a variable name as a string in PHP?
- JavaScript | Call a function after a fixed time
- How to remove error Call to undefined function curl_init()?
- How to call functions after previous function is completed in jQuery ?
- How to call a function automatically after waiting for some time using jQuery?
- JavaScript | Check if a variable is a string
- PHP | Check if a variable is a function
- How to check a variable is of function type using JavaScript ?
- How to change the value of a global variable inside of a function using JavaScript ?
- How to wait for a promise to finish before returning the variable of a function?
- Search in a sorted 2D matrix (Stored in row major order)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

