"In PHP, write a function "create" which takes an input $arg and returns another function which takes an input $ar (an array) and multiples each element of $ar by $arg."
As I said, I never used it before.
I had the impression that create_funtion() would be used on the fly, not really to create new (permanent) functions.
PHP Manual confirmed it by noting that one of its common uses is for callback functions in array_walk(), hence it is on the fly.
In your example, of course $x is undefined, since it isnt in the argument list.
You should use:
<?php
$f = create_function('$x, $arg','return $x + $arg;');
$x = 3;
print($f($x, 10));
?>
Of course this falls under your "why are you even creating a function in the first place" point, since it duplicates the functionality of
print $x + 10;
with no real advantage.
In your multiply by 3 case, I would use:
<?php
function foo(&$num, $index, $factor) {
$num *= $factor;
}
function create($factor) {
return create_function('&$array', 'array_walk($array, "foo", ' . $factor . ');');
}
$array = array(1, 2, 3);
$f = create(3);
$f($array);
print_r($array);
?>
This does what you want somewhat, though personally it would be difficult to maintain for a complex function foo().
The idea is that foo() takes in the value of an array element as a reference, and the corresponding array index.
It then takes in other arguments, in this case $factor
What ever needs to be done on the array element is done.
Now, array_walk() takes in an array, a callback function to apply to each element of the array, as well as other arguments.
This callback function is your crucial function foo().
If you ask me, I'd rather just write a function with some distinct identifiers, then do a search and replace for what the client wants before handing him the function.