Passing variable argument list to sprintf()
I would 开发者_如何转开发like to write a function that (amongst other things) accepts a variable number of arguments and then passes them to sprintf().
For example:
<?php
function some_func($var) {
// ...
$s = sprintf($var, ...arguments that were passed...);
// ...
}
some_func("blah %d blah", $number);
?>
How do I do this in PHP?
function some_func() {
$args = func_get_args();
$s = call_user_func_array('sprintf', $args);
}
// or
function some_func() {
$args = func_get_args();
$var = array_shift($args);
$s = vsprintf($var, $args);
}
The $args
temporary variable is necessary, because func_get_args
cannot be used in the arguments list of a function in PHP versions prior to 5.3.
use a combination of func_get_args
and call_user_func_array
function f($var) { // at least one argument
$args = func_get_args();
$s = call_user_func_array('sprintf', $args);
}
Or better yet (and a bit safer too):
function some_func(string $fmt, ... $args) {
$s = vsprintf($fmt, $args);
}
This is PHP 7.4, not sure if it works in earlier versions.
use $numargs = func_num_args(); and func_get_arg(i) to retrieve the argument
Here is the way:
http://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
basically, you declare your function as usual, without parameters, then you call func_num_args() to find out how many arguments they passed you, and then you get each one by calling func_get_arg() or func_get_args(). That's easy :)
精彩评论