Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function with unlimited number of parameters

Tags:

php

arguments

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);
like image 810
Ageis Avatar asked Oct 16 '09 10:10

Ageis


People also ask

How many parameters can a function have PHP?

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.

What is the maximum number of parameters a function can have?

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.

What is Variadic function in PHP?

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.

What can take multiple parameters in PHP?

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' .


1 Answers

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.

like image 135
Yacoby Avatar answered Sep 19 '22 16:09

Yacoby