create_function()
This creates a function that is stored in a variable instead of being named. These are commonly used as callback functions where you don’t need a function in the global namespace, but a function is required.
First you state your function’s arguments, secondly you give the body of the function. These are typically done with single quotes since you’ll likely want to use variables in your function but you don’t want to parse them as variables when you’re creating the function.
Let’s revisit our array_walk() example and do it with an anonymous function instead.
We get the same result but now we don’t have an extra function floating around polluting our environment.
$arr = array( 'A' => 'apple', 'B' => 'banana', 'C' => 'carrot', 'D' => 'durian' ); array_walk( $arr, create_function( '$word, $letter', 'echo "$letter is for $word\n";') ); /* A is for apple B is for banana C is for carrot D is for durian */
These functions can also be stored in a variable. This may be useful if you need to use it more than once. In a loop for example, create the function outside of the loop and save on having to create it multiple times inside the loop.
Here’s that same example but out function is in a variable.
$arr = array( 'A' => 'apple', 'B' => 'banana', 'C' => 'carrot', 'D' => 'durian' ); $func = create_function( '$word, $letter', 'echo "$letter is for $word\n";'); array_walk( $arr, $func ); /* A is for apple B is for banana C is for carrot D is for durian */
