[ Team LiB ] Previous Section Next Section

Dynamic Function Calls

You can assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Listing 6.5 creates a simple example of this.

Listing 6.5 Calling a Function Dynamically
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 6.5 Calling a Function Dynamically</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: function sayHello() {
12:   print "hello<br />";
13: }
14: $function_holder = "sayHello";
15: $function_holder();
16: ?>
17: </div>
18: </body>
19: </html>

A string identical to the name of the sayHello() function is assigned to the $function_holder variable on line 14. After this is done, we can use this variable in conjunction with parentheses to call the sayHello() function. We do this on line 15.

Why would we want to do this? In the example, we simply made more work for ourselves by assigning the string "sayHello" to $function_holder. Dynamic function calls are useful when you want to alter program flow according to changing circumstances. We might want our script to behave differently according to a parameter set in a URL's query string, for example. We could extract the value of this parameter and use it to call one of a number of functions.

PHP's built-in functions also use this feature. The array_walk() function, for example, uses a string to call a function for every element in an array. You can see an example of array walk() in action in Hour 7, "Arrays."

    [ Team LiB ] Previous Section Next Section