I saw many times that php developers use somthing like this:
if(null == $var){
}
while I use
if($var == null){
}
Are these two different? is there any reason to use each one? or it is a choice matter in any ways?
Simply null can't be assigned value
null = $a, it will throw parsing error.
but any variable can have null as value.
$a = null
So if you mistyped == to = in the second case, you have changed the value of $a and you check the if condition of the new value of $a which always evaluates to false.
Short answer, it's exactly the same thing. Long answer:
The C programming language allows assignment within the condition. e.g.
(i = 1)==1 is valid. This means that:
if (x = null)
is valid as well.
In some cases you intended to assign x = null but (most often) you just intended to compare x == null and mistyped.
Therefore developers in C (or C++) would do something like:
if (null == x)
This is because if it was mistyped to if (null = x) it would not compile.
However in PHP this is no longer a valid reason since PHP is not compiled therefore such errors are not trapped early and this defeats the whole purpose of the reversed syntax.
However, the advantage of using it in PHP is that when you do hit that part of the code, it will error instead of running normally and will therefore inform you of the problem.
On the other hand in PHP you should really use === so typos would lead to == anyway.
Related
This is a question that is bugging me for a long time and can't find any answer...
Noticed it's used quite a lot by Zend Framework Developers,
What is the difference between following 2 "if" statements? :
if (null === $this->user) { ... }
if ($this->user === null) { ... }
To me the first one looks kinda odd ;]
Thanks for answer.
This is not a difference for the way your script works, it's just a coding standard, a recommendation
The reason why it is recommended to use it this way:
if (null == $this->user)
is the fact that if you mistype and write = instead of == you will get an error, while
($this->user = null)
instead of
($this->user == null)
works but causes weird bugs (assignment and the final value is evaluated as bool instead of comparison)
and I guess it just extended as a habit to the strict comparison operator (===)
Update: since I see that there's still some activity on this thread even 3 years after I posted the answer I figured I would add something I forgot to mention. This type of notation is known as yoda conditions, you can read more about it on this wikipedia page for example.
It is a good practice for writing if statement. Consider this code:
if (10 == $var) {
echo 'true';
} else {
echo 'false';
}
If you forgot one equal sign:
if (10 = $var) { }
Then PHP will generate parse error, so you know you missed one = and you can fix it. But this code:
if ($var = 10) { }
will assign 10 to $var and always evaluates to true condition. Whatever the contents of $var, the code above will always echo 'true' and its very difficult to find this bug.
These are called yoda conditions.
The idea is that if you put the value first (such as false, null, true or anything short) it becomes easier for a person to scan the statement and quickly understand the intention of the condition.
Also, what mishu said :)
There is no difference in order when comparing values.
It may be easier for someone to read or write such a code, but to me it's the same as writing from right to left.
Such order of elements in comparison I think is meant to prevent accidental assignment in if statements.
The result will be the same, however, the second is logical.
You want to check if the variable is NULL, not if NULL is the variable...
The reason for doing it the other way around is described here:
http://umumble.com/blogs/Programming/321/
If you accidentally write:
if (null = $this->user) { ... }
you will get a syntax error.
If you accidentally write:
if ($this->user = null) { ... }
you will be searching for a reason of strange behavior of your application for a long time.
Compare:
if (donald_duck != null)
if (roast_potatoes > 9000)
if (love === 'explosions')
and
if (null != donald_duck)
if (9000 <= roast_potatoes)
if ('explosions' === love)
In the languages I've written in, I've always used the first order since it makes sense human-wise. e.g. "Is the parrot dead?" vs "Is dead what the parrot is?" However I've seen the (null == variable) order used a few times in various languages and places.
What operational difference does it make, and is one way more syntactically correct or widely adopted?
(I'm aware this may be different for various languages, so in particular I'm asking in regards to PHP)
There is no different in the behavior but it helps to avoid errors for example in the comparisons.
if you use obj == null to compare, you have some risk of making a mistake and putobj = null instead causing problems in your code and having unexpected results.
But if you use null == obj to compare, that risk goes away because null = obj is not a valid sentence (you can't assign an object to null) and you will receive an error in compile time.
Hope this helps
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP - reversed order in if statement
Checking for null - what order?
Examining Zend Framework found that they do all the variable checkings reverse way:
public function setBootstrap($path, $class = null) {
if (null === $class) { // instead of if($class === null)
$class = 'Bootstrap';
}
What's the reason of doing this?
Is this also suitable for Java and C++ programming?
some people believe it helps them in avoiding to write a single = (an assignment instead of a comparison for equality)
I believe that the advantage of doing so is much less than the loss of readability (and therefore maintainability!)
People who don't test their code may rely on this sort of trick. And to answer your question, yes, it is suitable for most languages who derive their syntax from C - I mean suitable, not recommended.
This style is called yoda conditions.
Basically it has the same behavior as the usual ( $variable === value ) style, but with one advantage:
The compiler throws an error in case you write = instead of == or === by mistake.
As you can't reassign a constant (in the example the null value), the developer immediately recognizes the mistake due to a compiler error/warning and thus is relieved of a time consuming bug search.
So the following line would be valid, although it wont show the (most of the time) intended behavior:
if ( $var = null ) { echo 'test'; }
While here an error is shown:
if ( null = $var ) { echo 'test'; }
A major drawback, however, is the loss of readability with this style. But this depends on the reader of the code and some other coding style guidelines.
This is a yoda condition, I dont know about any benefits except you cant assign the value to the variable when you accidentally write for example
if( $foo = "bar" )
Here a Link for more examples:
http://united-coders.com/christian-harms/what-are-yoda-conditions
In this case comparison takes in account value and a type of the value. this is a strict comparison.
For example this code:
if (null == "") {
echo "null";
}
Will print "null" as far as PHP treats "", 0, null, false as equivalent empty values unless strict comparison is used to compare actual value and type of the value itself.
Second thing is why null === $class is used is because you can not assign value to null. Whereas you can successfully make mistake and assign $class = null.
What is the difference between the 2 statements:
if (false === $variable) {
//do something
}
and
if ($variable === false) {
//do something
}
I personally use the second style but often run into code in frameworks that i use which always seem to use the first style.
Is there a difference ( i suspect it is some legacy thing to do with types) or is this simply a coding habit (it must be rooted in something though??)
If not, what is the reasoning behind the first style given that the logic is actually backwards.
if ($foo = false) (note: = instead of ==) is a typical typo that leads to hard to debug problems. For that reason, some people prefer false == $foo, since the runtime will throw an error when you try to assign something to false.
Other than that there's no difference.
If you put the value that can't have something assigned to it (a literal, a constant, a function call, etc) on the left hand side then, if you accidentally use an assignment operator (=) instead of a comparison operator, then you'll get an error rather then a hard-to-track-down bug.
i.e.
if (false = $variable) { // Error
if ($variable = false) { // Valid code that doesn't do what you want
This dates to C programming. It's a way to make sure "compilers" will fail if you accidently used = (assignment) and not == or === (equals) because "false" is not an lvalue (can't be on the left side of an assignment)
It stems from this:
if (false = $variable)
syntax error
if ($variable = false)
accidental assignment
It has been around for a while. It comes from accidentally writing (by forgetting one =):
if (c = 1) {
}
which does assignment and it's doesn't actually check whether c equals 1. It assigns 1 and then it evaluates to 1 (so the if statement becomes always true due to that mistake). By writing
if (1 == c) {
}
as a habit, you cannot make that mistake. If you would forget the = in this case, the compiler would warn you because assignment to the literal 1 is not possible.
Practically, the two statements are equivalent.
So, why to write it this way or the other (?) :
Try to avoid a typical typo : if ($condition = false) instead of if ($condition == false). In that case, your 2nd version would cause a difficult-to-debug issue, while the first would throw an error
Want to force one of the two parts of the conditional statement be evaluated first (the rightmost)
a)
if(null === $object)
{
//take some action
}
b)
if($object === null)
{
//take some action
}
I am in habit of doing like b) but in Zend-Framework I find everywhere they have done it like a) . Is there any benefits of it ??
Thanks.
No, there is no difference.
The latter is supposed to help to avoid silly typos when you write $a = null instead of $a == null (or $a === null). In first case you'll get logical error, because of assignment instead of comparison, in second case - you'll get fatal error which will help you to find an issue sooner.
There is no difference, it is used to avoid mistakes (like setting variable to null, not comparing them), however the null === $object is often considered the Bad Way (c) to avoid typos.
The $object === null expression is much more human-friendly then null === $object 'cause second one breaks nature reading order which is left-to-right. That's why even if there is no much difference for interpreter but it's a bit harder to read by a human. Involving some logic - if you use if..else statement how it should sounds like? "If null equals $object.. Wait a minute, null is null, how can it be equal to something else? Oh, Gee, we actually comparing right-handed value to left-handed one, it's reversed stuff. So, if $object equals null then we should..". And your think this way every time.
My conclusion is: use $value == const every time you can! Long time ago people wrote if ($value = const) but these times have passed. Now every IDE can tell ya about such simple errors.
b) is way more readable than a)
And a) is considered by some overcautious people as less error prone because of possible confusing == with =.
But in case of three ='s I doubt anyone will confuse it with one.
This a choice by the developer to attempt to stop accidential assignment of values.
The functionality is exactly the same between the two methods of comparison but in the case of "a" it stops any accidential assignment of values as you cannot assign something to null.
The second method checks the value and type of variable against null, The errors should be different in tow methods.