PHP: Collect all variables passed to a function as array?
I was thinking about the possibility of accessing all the variables that are passed into an function, and merge them into an array. (Without passing variables into an array from the beginning)
Pseudo-code:
// Call function
newFunction('one', 'two', 'three' ) ;// All values are interpreted as a one rray in some way
// Function layout
newFunction( ) {
// $functionvariables = array( All passed variables)
f开发者_StackOverflow社区oreach ($functionvariable as $k => $v) {
// Do stuff
}
}
http://php.net/func_get_args
Take a look at func_get_args
function. This is how you can build an array for them:
function test()
{
$numargs = func_num_args();
$arg_list = func_get_args();
$args = array();
for ($i = 0; $i < $numargs; $i++)
{
$args[] = $arg_list[$i];
}
print_r($args);
}
It can be useful to clearly identify that the items you are passing in should be treated as an array. For instance, set your function def to
function newFunction( $arrayOfArguments ) {
foreach($arrayOfArguments as $argKey => $argVal)
{ /* blah */ }
}
精彩评论