User Tools

Site Tools


conventions:php_null

The absence of value

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:

  1. As noted in PHP's documentation, the constant null forces a variable to be of type null;
  2. A variable with null value returns false in an isset() test, despite that, assigning a variable to NULL is not the same as unsetting it. To actually test whether a variable is set or not requires adopting different strategies per context (https://stackoverflow.com/a/18646568).
  3. The void return type doesn't return NULL, but if used as an expression, it evaluates to null.

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.

We've put to vote two options

Option 1: Use === null (most of the time)

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).

Option 2: Use is_null()

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).

Results

Voter is_null() === null
XRevan86 X -
Diogo X -
Hugo - X
Eliseu X X
conventions/php_null.txt · Last modified: 2021/12/08 00:28 by diogo