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 ...

Get Sams Teach Yourself PHP in 24 Hours, Third 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.