5

Running CodeSniffer PHP style tests gave me the following error:

The use of function is_null() is forbidden    
Squiz.PHP.ForbiddenFunctions.Found

Why would use of is_null() be forbidden?

8128
  • 969
  • 1
  • 8
  • 27

1 Answers1

9

We implemented this rule in the Squiz standard for consistency.

Another part of the standard forbids implied expressions, for example if ($var) {.... So you need to write if ($var === TRUE) {....

Due to this, a comparison of a NULL value would look like this:

if (is_null($var) === TRUE) {
}

Given the fact you already have to write the second half of the comparison, it is easier to just write:

if ($var === NULL) {
}

The code is simpler this way, but also (and more importantly) more consistent with the way we do things.

That's the only reason. We weren't concerned about performance and didn't have any issues with the is_null() function itself. It works fine as far as I know.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Greg Sherwood
  • 6,992
  • 2
  • 29
  • 24
  • 3
    But isn't the result of `$var === TRUE` another boolean? So you should actually write `($var === TRUE) === TRUE`. And so on and on.... – maaartinus Jun 05 '14 at 04:07
  • Yes, the result is a boolean, which is the point. `$var` itself may not be a boolean, but the IF statement will cast it to one and interpret the result. Forcing an equality and type check with `===` just ensures that developers (both writing and reading the code) are aware of what values they are storing and using. – Greg Sherwood Jun 15 '14 at 22:37
  • I see... but you're basically redefining the truthy values and `$var === TRUE` is something different from `$var !== FALSE` unless you can be sure `$var` is a `boolean`. I personally made a bad experience with it in another language. – maaartinus Jun 15 '14 at 23:25
  • Yes, just because `$var !== TRUE` doesn't mean `$var === FALSE`. But when your checking vars like `$isConnected`, we don't really care what the value is if it isn't `TRUE`; you're obviously not connected even if the value is `0`, `NULL`, `FALSE`, or `'error219'`. But if I just use `if ($isConnected) {...` and the value is `'error219'` then that IF statement is going to evaluate to `TRUE`, which I don't want. If you are checking different values, you may very well need a few ELSE clauses in there, depending on how important the exact value is. – Greg Sherwood Jun 16 '14 at 22:27