Reputation: 11233
Should empty function arguments be set to NULL
or FALSE
?
As example follows:
function test1($a = FALSE, $b = FALSE)
{
if ($b)
{
// ... (some awesome code here)
}
//.. (more awesome code)
}
test1(0);
OR
function test2($a = NULL, $b = NULL)
{
if ($b !== NULL)
{
// ... (some awesome code here)
}
//.. (more awesome code)
}
test2(0);
Note; Also something to consider - while using $a === NULL
. One could also use '!empty()
' depending if the below code requires empty values or not.
Which is a better design and why?
Upvotes: 0
Views: 77
Reputation: 36934
Logically a NULL
value should treat as something that doesn't exist. FALSE
instead has some semantic value, even if you can consider it as an empty value.
So, use FALSE
for an answer to yes or no, NULL
as no answer.
If your argument is an option like $enable_this
it can be a boolean value, and you may want check if it's true with
if ($var)
Instead if you can optionally pass something as an argument, by default it can be NULL
, and then you can check if it's really there with
if($var !== null)
You should use empty
only if you want test it to empty value. Cannot $var
be an empty string, an empty array, "0"
or 0
?
Upvotes: 2
Reputation: 334
You could also do it like this:
function test1($a = FALSE, $b = FALSE) {
if ($b===false) {
// ... (process default val-false)
}else{
//.. (process supplied value)
}
}
Upvotes: 0
Reputation: 6110
Use this
function test($a = NULL, $b = NULL)
{
if ($b !== NULL)
{
// ... (some awesome code here)
}
//.. (more awesome code)
}
test(0);
Dont use if(!empty($b))
, if($b!=NULL)
and if(!is_null($b))
because $b=false
&& $b=0
will fail in this case
Upvotes: 2