问题
Hell, I can't even FIND the documentation for 'use' on the PHP site (other than in the context of namespaces - nice job ambiguating a keyword BTW).
Can someone confirm that function() use ($foo) { }
is only available in 5.3 and later? And where did you find that documented?
As an added bonus, how would you code around not being able to use 'use' (eg: with create_function($args, $funcname) as the callback for array_map())?
回答1:
Closures are introduced in 5.3, thus use
in conjunction with closures are also available in 5.3 or later (of course).
As an added bonus, how would you code around not being able to use 'use' within a closure
I don't understand the question completely, but because both closures and use
with closures comes with the same version, there is no situation, where you can not use use
with closures. Either both, or nothing (--> <5.3)
http://php.net/functions.anonymous
Release Notes 5.3.0
回答2:
In the absence of closures, in a pre 5.3 world, if you want to avoid create_function() but need to bind variables from an external scope to a callback type function, wrap the function in a class, to which you pass your external variables upon instantiation.
If you do this a lot, you may find the following generic wrapper class useful (or ugly, or both as do I):
class GenericCallbackWrapper {
function __construct (){
$argIndex = 1;
foreach(func_get_args() as $value){
$argName = 'user' . $argIndex;
$this->$argName = $value;
}
}
public function example_strip_prefix($a){
return substr($a, strlen($this->user1));
}
}
I would actually put this in an external file (callbacks.php) and then just keep adding your callback code a public methods of this class. Obviously, this only pays dividends if you're going to do this frequently; otherwise, just create a one-off wrapper class whose constructor accepts the specific number of arguments you're looking to include.
This generic code can then be leveraged using the two-argument form for specifying a callback:
function get_input_field_IDs_by_prefix($prefix){
return array_map(
array(new GenericCallbackWrapper($prefix), 'example_strip_prefix'),
preg_grep('/^'.$prefix.'/', array_keys($_REQUEST))
);
}
The generic wrapper takes any number of arguments and adds them as member (instance) variables to the class that can then be accessed in order as $this->user1, $this->user2 etc (initial index is 1).
Hope this is of some use to someone. At some point. Maybe.
来源:https://stackoverflow.com/questions/6347509/is-the-use-keyword-available-for-function-closures-pre-5-3