tags:

views:

358

answers:

4

What's the best way to structure a function, that has parameters that can be null?

Eg

    function newDate($day, $time = null, $overRide) {

        Do something with the variables

    }

# newDate('12', '', 'yes');

Would it be to simply restructure the function as follows:

    function newDate($day, $overRide, $time = null) {

        Do something with the variables

    }

# newDate('12', 'yes');
A: 

The issue isn't parameters that can be null. Any parameter can be null, just by passing it to the function. What's causing the difficulty here is the default value. Parameters with a default value have to be at the end since it's simpler for the compiler to assume that anything that comes before them is part of the fixed arguments.

Ignacio Vazquez-Abrams
+2  A: 

I don't think you have a choice, actually.

The default parameters should be last ones on your function. Otherwise, when you call newDate(1, 2), PHP will turn it into newDate(1, 2, null) where you may have wanted newDate(1, null, 2).

See PHP's documentation on function arguments.

pgb
A: 

What you've outlined (i.e.: moving the optional args after the required ones) makes sense only as long as the 'flow' of the arguments still makes sense. (i.e.: Only if they don't need to be in a specific order to make sense.) However, it's still the best means of achieving your goal.

That said, if there are potentially a large number of optional arguments, it might be an idea to accept an optional array which would contain key=>value pairs of the optional args to check for.)

(Incidentally, in your first example, your should really pass null instead of ''.)

middaparka
A: 

It better to define default parameters at the end of function declaration..

when having nullable or default parameter in the center, calling looks like:

newDate($someDay, null, $override);

however having default arguments at the end, provides a simpler function calling:

newDate($someDay, $override); // null is passed for $time
Juraj Blahunka
It's not a matter of style, but a matter of language support. PHP only supports optional parameters at the end of the arguments list.
pgb