Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Function Definition, Null Arguments

Tags:

function

php

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');
like image 733
Sjwdavies Avatar asked Feb 18 '26 22:02

Sjwdavies


2 Answers

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.

like image 189
pgb Avatar answered Feb 20 '26 11:02

pgb


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
like image 30
Juraj Blahunka Avatar answered Feb 20 '26 11:02

Juraj Blahunka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!