Skip to content
Advertisement

Using Default Arguments in a Function

I am confused about default values for PHP functions. Say I have a function like this:

JavaScript

What if I want to use the default argument for $x and set a different argument for $y?

I have been experimenting with different ways and I am just getting more confused. For example, I tried these two:

JavaScript

But both of those do not result in a proper default argument for $x. I have also tried to set it by variable name.

JavaScript

I fully expected something like this to work. But it doesn’t work as I expected at all. It seems like no matter what I do, I am going to have to end up typing in the default arguments anyway, every time I invoke the function. And I must be missing something obvious.

Advertisement

Answer

I would propose changing the function declaration as follows so you can do what you want:

JavaScript

This way, you can make a call like foo('blah', null, 'non-default y value'); and have it work as you want, where the second parameter $x still gets its default value.

With this method, passing a null value means you want the default value for one parameter when you want to override the default value for a parameter that comes after it.

As stated in other answers,

default parameters only work as the last arguments to the function. If you want to declare the default values in the function definition, there is no way to omit one parameter and override one following it.

If I have a method that can accept varying numbers of parameters, and parameters of varying types, I often declare the function similar to the answer shown by Ryan P.

Here is another example (this doesn’t answer your question, but is hopefully informative:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement