O'Reilly logo

Core PHP Programming, Third Edition by Leon Atkinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

4.7. Dynamic Function Calls

You might find yourself in the position of not knowing which function should be called when you are writing a script. You want to decide based on data you have during execution. One way to accomplish this is to set a variable with the name of a function and then use the variable as if it were a function.

If you follow a variable with parentheses, the value of the variable will be treated as the name of a function. Listing 4.11 demonstrates this. Keep in mind that you can't refer to built-in functions in this way. Setting myFunction to be print will cause an error.

Listing 4.11. Calling a function dynamically
 <?php function write($text) { print($text); } function writeBold($text) { print("<b>$text</b>"); } $myFunction ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required