When programming in PHP it's common having to represent the absence of value. A variable that wasn't initialized yet or a function that could not produce a value. On the latter, one could be tempted to throw an exception in these scenarios, but not always that kind of failure fits the panic/exception/crash category.
On the discussion of whether to use === null
vs is_null(),
the literature online is diverse and divided.
Some facts to consider:
About nullable types,
we prefer that you use the shorthand ?T
instead of the full form T|null
as it suggests that you're considering the
possibility of not having the value of a certain variable. This apparent intent is reinforced by the fact that NULL can
not be a standalone type in PHP.
Use one, or the other in function of context. This is better illustrated with two example situations:
If you're testing if a function returned null, then you're not testing a variable's data type, you're testing
whether it evaluated to null or not. So, as you normally would with a === true
or === false
, we prefer
that you test as === null
in this situation.
If you're testing whether a variable is of type null, then you should use is_null($var)
. Just as you normally
would with a is_int($var)
or is_countable($var)
.
Considering union types and what we use null
to represent, we believe that our use of null is always akin to that of
a Option type. Here's an example:
function sometimes_has_answer(): ?int { return random_int(1, 100) < 50 ? 42 : null; } $answer = sometimes_has_answer(); if (!is_null($answer)) { echo "Hey, we've got an {$answer}!"; } else { echo 'Sorry, no value. Better luck next time!'; }
A non-void function, by definition, is expected to return a value.
If it couldn't and didn't run on an exceptional scenario, then you should test in a different style from that of regular
strict comparison. Hence, as you're testing whether a variable resulting of a union of types is of type null, then you should use is_null($var)
. It's about verifying if a variable is in a state in which holds a value.
Just as you normally would with an is_int($var)
or is_countable($var)
.
Voter | is_null() | === null |
---|---|---|
XRevan86 | X | - |
Diogo | X | - |
Hugo | - | X |
Eliseu | X | X |