Pregunta

I'm relatively new to programming, have been working a lot in javascript, and now trying to learn php. The title basically says it. How many parameters can I pass in a user defined function?

I've noticed standard functions tend to accept different numbers, so I was wondering if I could potentially pass infinite numbers of parameters in a function call, so long as the function does something with each.

for example:

Call the function:

Myfunction(1,4,3,2,6)

The function being called:

function Myfunction(numOfApples, numOfBananas, numOfPears, numOfOranges, numOfRasberries){'do something with each of these values'}

I'm asking for general understanding, I'm not trying to do anything specific, so the fruit list thing is just an example of passing parameters that represent different things.

¿Fue útil?

Solución

I don't believe there is a limit on the number of parameters you can send into a function. However, in my opinion once you get over about 3 or 4 I tend to move towards sending in an array or object like so:

$send_values = array(
    'value1' = 1,
    'value2' = 3,
    'value3' = 2,
    'value4' = 5,
    'value5' = 1,
);

function Myfunction($input) {

}

This way you don't have to worry about the exact order you are sending in the variables. Plus sending null values is much easier. You can simply use isset($input['value2']) to see if a value was sent. But if each was set as in independent variable you have this issue:

function Myfunction(value1,value2,value3=null,value4=null,value5=null) {

}

In this case value1 and value2 are required to be sent in, but value 3,4 and 5 can be null. So if you are just sending the first two values you can simply do this:

Myfunction(1,2);

However lets say you need to send in value1 value2 and value5, now you have to make sure you send null values for value3 and value4, so that value5 gets populated with the data not value3:

Myfunction(1,2,null,null,5);

In my opinion this can just turn into a cluster and can get confusing. It is all personal preference, there are some good answers on this question: How many parameters are too many?

Otros consejos

There isn't really a limit. But if the number of parameters starts to pile up, you should consider making an object to store these ( assuming they are related, like in your example), and pass the object through as a parameter.

Passing an object, or array for that matter, makes it easier to make modifications to your code at a later point in time ( rather than having to update the parameter field every time you make changes).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top