How to call PHP function from string stored in a Variable
Last Updated :
02 Nov, 2018
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 func() {
echo "geek" ;
}
function fun( $msg ) {
echo $msg ;
}
$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 func() {
echo "hello " ;
}
function fun( $msg ) {
echo $msg . " " ;
}
$var = "func" ;
$var1 = "fun" ;
$var ();
$var1 ( "geek" );
echo "\n" ;
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 writeMessage() {
echo "Welcome to GeeksforGeeks!" ;
}
$functionName = "writeMessage();" ;
eval ( $functionName );
?>
|
Output:
Welcome to GeeksforGeeks!
Share your thoughts in the comments
Please Login to comment...