How do you write a function in PHP that can accept an unlimited number of arguments similar to sprintf?
sprintf("one:%s",$one);
sprintf("one:%s two:%s",$one,$two);
...
Example from php.net
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
Easily. Declare your function with the static arguments
function myprintf ($string)
and get hold of the unlimited additional arguments using func_get_args() .
A function can accept as many parameters as you want ; it just has to deal with them using the following functions : func_num_args
, func_get_arg
, and func_get_args
.
Examples are given on those three manual pages, but here's the one from the func_get_args
page (quoting) :
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
And the output will be :
Number of arguments: 3<br />
Second argument is: 2<br />
Argument 0 is: 1<br />
Argument 1 is: 2<br />
Argument 2 is: 3<br />
使用func_get_args()
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.