PHP - Function Variable Functions


You can store the name of a function in a string variable, and use that variable instead of the function name when calling a function.

Here's an example:


$squareRoot ="sqrt";
echo"The square root of 9 is:". $squareRoot(9).". \n";
?>//from w  w w . ja  v a2s.  c  o m


The first line of code stores the function name, "sqrt", as a string in the $squareRoot variable.

This variable is then used in place of the function name on the second line.

Another example:



         $trigFunctions = array("sin","cos","tan");
         $degrees = 30;/*from ww  w .j a  v  a  2s  . c  o  m*/

         foreach ($trigFunctions as $trigFunction) {
             echo"$trigFunction($degrees) =". $trigFunction(deg2rad($degrees))."\n";


Here, the code creates an array of three built-in function names - "sin", "cos", and "tan" - and sets up a $degrees variable.

It loops through the array.

For each element, it calls the function whose name is stored in the element, passing in the value of $degrees converted to radians using PHP's built-in deg2rad() function), and displays the result.

Related Topic