Variable Functions

As with variable variables where the expression refers to the value of the variable whose name is the value held by the apparent variable (the $$ construct), you can add parentheses after a variable to call the function whose name is the value held by the apparent variable, e.g., $variable(). Consider this situation, where a variable is used to determine which of three functions to call:

switch ($which) {
  case 'first':
    first();
    break;

  case 'second':
    second();
    break;

  case 'third':
    third();
    break;
}

In this case, we could use a variable function call to call the appropriate function. To make a variable function call, include the parameters for a function in parentheses after the variable. To rewrite the previous example:

$which();  // if $which is "first", the function first() is called, etc...

If no function exists for the variable, a runtime error occurs when the code is evaluated. To prevent this, you can use the built-in function function_exists() to determine whether a function exists for the value of the variable before calling the function:

$yesOrNo = function_exists(function_name);

For example:

if (function_exists($which)) {
  $which();  // if $which is "first", the function first() is called, etc...
}

Language constructs such as echo() and isset() cannot be called through variable functions:

$which = "echo";
$which("hello, world");  // does not work

Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.