Dynamic Function Calls

It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function names themselves. Listing 6.5 shows a simple example of this.

Listing 6.5 Calling a Function Dynamically
   1: <html>   2: <head>   3: <title>Listing 6.5</title>   4: </head>   5: <body>   6: <?php   7: function sayHello() {   8:     print "hello<br>";   9: }  10: $function_holder = "sayHello";  11: $function_holder();  12: ?>  13: </body>  14: </html> 

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

Put these lines into a text file called sayhello.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:


Why would we want to do this? In the example, we simply make 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 can extract the value of this parameter and use it to call one of a number of functions.

Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
ISBN: 067232489X
EAN: 2147483647
Year: 2005
Pages: 263

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net