PHP Tutorial : Dynamic Function Calls

Leave a Comment

It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Below code creates a simple example of this.
<html>
<head>
<title>Listing 6.5</title>
</head>
<body>
<?php
function sayHello()
{
print "hello<br>";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>

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

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 make use of this feature. The array_walk() function, for example uses a string to call a function for every element in an array.

0 comments:

Post a Comment