How do I write a function that can accept unlimited number of parameters?
What am trying to do is create a function within a class that wraps the following:
$stmt->bind_param('sssd', $code, $language, $official, $percent);
PHP native functions According to the manual, PHP functions may accept up to 12 arguments. This is the case for two functions : imapepstext and snmp3_set.
Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.
Variadic functions allow you to declare an array of incoming parameters, and argument unpacking allows you to pass an array in to a function expecting separate parameters in the traditional way; they are absolutely complementary to one another.
Introduction to the PHP function parameters When a function has multiple parameters, you need to separate them using a comma ( , ). The concat() function has two parameters $str1 and $str2 . In this example, the $str1 will take the first argument 'Welcome ' , and the $str2 will take the second argument 'Admin' .
Have you taken a look at func_get_args, func_get_arg and func_num_args
So for example:
function foo(){
if ( func_num_args() > 0 ){
var_dump(func_get_args());
}
}
or:
function bind_param(){
if ( func_num_args() <= 1 ){
return false; //not enough args
}
$format = func_get_arg(0)
$args = array_slice(func_get_args(), 1)
//etc
}
EDIT
Regarding Ewan Todds comment:
I don't have any knowlege of the base API you are creating the wrapper for, but another alternative may be to do something with chaining functions so your resulting interface looks something like:
$var->bind()->bindString($code)
->bindString($language)
->bindString($official)
->bindDecimal($percent);
Which I would prefer over the use of func_get_args as the code is probably more readable and more importantly less likely to cause errors due to the the lack of a format variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With