Advanced PHP Variables and Functions
Pages: 1, 2, 3
Dynamic function creation
Beyond calling functions dynamically, it is also possible create functions dynamically. This can be done through the use of the create_function() function in PHP. The syntax of this function is as follows:
string create_function(string args, string code);
When called, we pass to the function two parameters. The first, args, is a string that contains the code that would normally go between the parentheses of a function declaration. The second parameter code is a string representation of actual PHP code that consists of what normally would be the body of a given function. When the create_function() is called, it creates the function as specified and returns a variable containing the name of that function that you can then use to call the function. Let's take a look at an example:
<?php
// Normal function definition
function my_normal_func($foo, $bar) {
echo "Hi, PHP!";
}
// Dynamic function definition
$func_name = create_function('$foo, $bar',
'echo "Hi, PHP!";' );
?>
In this example, we create two functions that are identical in output. In the first example, we declare prior to the script's execution and we name it my_normal_func(). In the second example, we create the function with a call to create_function(). When we execute the script, the function will be created and the name assigned to the function will be stored in the variable $func_name and will have the exact same code and parameters as the function we declared. This process can be useful in a number of circumstances (such as creating callback functions or data validation functions), and it is recommened that you read the manual entry on create_function() available on php.net for more information on how to use this function in everyday coding practice.
Final notes
With PHP, it is possible to create extremely complex, nearly self-creating programs that produce excellent results with a minimal amount of development time. As with almost every powerful tool, improper and careless use of dynamic programming can result in serious security leaks. Never base dynamic code on direct input from the user without first checking to ensure it contains no harmful or malicious code before creating functions or executing commands (particularly dynamic ones) based on it. Until next time -- happy coding!
|
Also in PHP Foundations: |
John Coggeshall is a a PHP consultant and author who started losing sleep over PHP around five years ago.
Read more PHP Foundations columns.
Return to the PHP DevCenter.