Funciones PHP: número máximo de argumentos

In PHP, when defining a function what is the maximum number of arguments that you can create? This isn't something I am doing, just a question that popped up when discussing it with a colleague :)

Would this be purely down a memory limitation? effectively unlimited?

preguntado el 08 de noviembre de 11 a las 11:11

I'm very grateful he didn't, but asked instead. You see, this way we don't all have to, either. SO has just served the community wonderfully again. -

4 Respuestas

There is no limit. And you can always use func_get_args(), func_get_arg() y func_num_args() to avoid writing all the arguments in the function definition.

respondido 08 nov., 11:15

Arguments to a function are pushed on a stack, after which the function is called which in turn reads the stack and uses those values as parameters.

So as long as the stack isn't full, you can keep adding parameters, but it'll depend on the situation, and at design-time you won't know the stack size.

But I really hope this is pure a technical discussion and you don't need it IRL. ;-)

respondido 08 nov., 11:15

haha, no no, as I mentioned this isn't IRL - purely technical ramblings :-) - bagwaa

when defining a function what is the maximum number of arguments that you can create?

I'm not aware of specific limit in the number of arguments as a fixed number. A quick test revealed that I had no problems to define a function with 255 555 arguments. It does take some time to define the function and to execute it. However, it works.

As the number was raised, I was running into a memory limit which could be string limit. You might want to improve the test-case, use a buffer and save the file to disk sequentially and include it then:

$count = 255555;

$code = 'function test(%s) {return 1;}; return test();';

$params = ltrim(implode('=0, $p', range(0, $count)), '0, =').'=0';

echo eval(sprintf($code, $params));

respondido 08 nov., 11:15

I don't really know what are the limits, but either way, if you create a function with too many arguments your code will not be so easy to read it. In case you like to add many function arguments you can do something like that:

$option = array(
    'arg_1' => 'value',
    'arg_2' => 'value',
    ....
    'arg_x' => 'value'
);

function function_name($args = "")
{
    $defaults = array(
        'arg_1' => 'default_value',
        'arg_2' => 'default_value'
        ....
        'arg_x' => 'default_value'
    );

    $arguments = array_merge($defaults, (array)$args);
    extract($arguments);

    echo $arg_1;
    echo $arg_x;
}

Respondido el 18 de enero de 17 a las 15:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.