Creating Variable Functions

You want a function to be called at run time, so that you can pass the name of the function to some other code. To do so, a variable can hold the name of a function, and the function can be called just by including parentheses after the variable.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
function fruits($arg)
  {
  echo "We serve $arg for dinner.<br />";
  }
// The variable has a value that is the name of the function.
$what_fruits = "fruits";
// The argument does not have to be inside a quote
$what_fruits = "fruits";
$what_fruits(grapes);
$what_fruits(strawberries);
?>
</p>
</body>
</html>

View the effect


Functions | What is a Function? | Defining a Function | Calling a Function | Passing Data | Variable Scope | Global Access | Setting Default Values for Arguments | Passing Arguments by Reference | Returning Values from Functions | Returning References from Functions | Static Variables | Creating Variable Functions | Creating Conditional Functions | Creating Functions within Functions | Include Files | Require Statement | Testing a Function | Type-Testing Functions | Handling Errors Returned by Functions
© 2008: Hann So
email: hso@voyager.deanza.edu