How do I pass a variable to create_function() ?
I have something like this:
function my_hook_functi开发者_运维百科on(){
$var = 10;
apply_filters('hook', $var);
return $var;
}
$variable = 5;
$function = create_function('', 'return $variable;');
add_filter('hook', $function);
echo my_hook_function();
but it doesn't work :( theoretically the output should be 5
add_filter() is a wordpress function that allows you to change stuff around :)
There are two problems here. The first one is that you need to tell php what parameters get passed to the 'created' function, or reference them as a global inside of the body. The second is that you are expecting $var to be modified by the created function, but you are not passing it a reference. the created function simply returns the new variable and you do nothing with it.
function my_hook_function(){
$var = 10;
$var = apply_filters('hook', $var);
return $var;
}
/* This will return 5 by dividing the passed value by 2 and returning the result */
$function = create_function('$variable', 'return $variable/2;');
add_filter('hook', $function);
echo my_hook_function();
/* This will return 5 by referencing the global $variable */
$variable = 5;
$function = create_function('', 'global $variable; return $variable;');
add_filter('hook', $function);
echo my_hook_function();
Note that if you run this code exactly like this that both of the filters will be added to the 'hook' hook.
$outsideVarName = 3434;
$function = create_function('$insideFunctionVarName', 'return $insideFunctionVarName;');
echo $function($outsideVarName);
Reading the manual for create_function the usage for passing $variable
to the function would be as follows:
$variable = 3434;
$function = create_function('$v', 'return $v;');
echo $function($variable);
EDIT
Changed $variable
inside the create_function
call to make it a bit clearer of proper usage and avoid confusion.
UPDATE
Given the comment below, here is an updated version:
$variable = 3434;
$function = create_function('$v', 'return $v;');
function myTest($function, $var) {
echo $function($var);
}
myTest($function, $variable); // should echo 3434
Not sure if that is what you want, I will refrain from guessing further till you show the actual context you are working in.
Update 2
Doing some research, is there a reason you do not just use it in this manner:
add_filter('something', create_function('$v', 'return $v;'));
From what I could find that should work...
I think what you really want is
$function = create_function('', "return $variable;");
or
$function = create_function('', 'return ' . $variable . ';');
i.e. you want to capture the value of the variable into the function when created. Since a number converted to a string is the same as its source representation, simply interpolating it into the source of the function is sufficient. For strings and arrays, some quoting will be necessary.
精彩评论