With the ability to call functions dynamically we can call functions while the script is running even if we don't know the name of the function at design time. The following example illustrates their use.
|
<?php
function hello($name)
{
print "Hello $name<br>";
}
$dynamic = "hello";
$dynamic("John"); ?> |
This will print "Hello John". As you can see we can call a function adding parenthesis (and the required parameters) to any variable that have a string as a value.
You can also use this feature to call functions within an object like in the following example.
<?php class myclass { function hello($name) {print "Hello $name<br>"; } }
$myobject = new myclass(); $dynamic = "hello"; $myobject->$dynamic("John"); ?> |
This will also print "Hello John". In the above example we are dynamically calling the method hello of our object ($myobject). Notice that the codes of both examples are almost the same.