Often, I see in if statements for php something like this:
if (null === $variable) {
// do stuff
}
What does it do and what is it for?
EDIT: I totally get that it is a comparison operator, I just wonder why not $variable === null
.
Often, I see in if statements for php something like this:
if (null === $variable) {
// do stuff
}
What does it do and what is it for?
EDIT: I totally get that it is a comparison operator, I just wonder why not $variable === null
.
It's not an assignment, it's a comparison for equality. It determines if the variable $variable
contains the value null
.
More in the documentation:
why not to check
$variable === null
Some people like to use the form with the constant on the left (a "Yoda condition", it is called) so that if they have a typo and only type a single =
, it causes a syntax error rather than doing an assignment.
That is the Yoda style usually used as a trick by programmers to prevent accidental assignments which always give some silent bugs.
Example:
var a = dosomething();
if(a = null){
//more here
}
Note that the if block will always not execute regardless of the result of doSomething
method since we assign then check for equality. This assignment nullifies the possibly non-deterministic nature of doSomething