Difference between variable === value and value === variable? - php

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.

Related

Comparison complexity from left to right [duplicate]

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.

php - which one is better approach null== or ==null

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.

PHP - reversed order in if statement

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.

What's the meaning of the reverse entry (null === $value) when checking the value of the variable? [duplicate]

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.

Why isset() is more efficient to test than '==='?

Summarized, I made a loop with a few iterations to check the efficiency of each test:
$iterations = 99999999;
$var = null;
isset comparasion
if ( isset( $var ) )
{
}
'===' comparasion
if ( $var === null )
{
}
And i have this log, in microseconds:
'isset()': 1.4792940616608
'===': 1.9428749084473
For me, this is a little curious. Why isset() function is faster than one comparison operator as ===?
The === comparison is a strict check, meaning that the two objects you're comparing have to be of the same type. When you break it down in plain English, it's actually not that weird that === needs some more time. Consider the parser to do this:
if (isset($var)) {
// Do I have something called $var stored in memory?
// Why yes, I do.. good, return true!
}
if ($var === null) {
// Do I have something called $var stored in memory?
// Why yes, I do.. good! But is it a NULL type?
// Yes, it is! Good, return true!
}
As you can see, the === operator needs to do an additional check before it can determine if the variable matches the condition, so it's not that strange that it is a little bit slower.
Isset is not a function: it is a language built-in. Using isset is faster than using a function.
The other thing is that isset is used all over the place, so it makes sense that it's been profiled to death, whereas === maybe hasn't received as much love.
Other than that, you'd have to dig in the PHP source with a profiler to see exactly what's going on.
I'm not sure I would call 100 million "a few iterations". You appear to have accumulated about a half-second difference, divide that by 100 million and you get a whopping 5 nanosecond difference per iteration if my math is correct. With the difference being so small it may simply come down to the fact that isset only has one operand in this context and === has two.
It's impossible to even discuss the Zend engine's implementation details of the two examples without specifying a specific PHP version; source code is a moving target. Even minute changes to the implementations are going to effect the results over that many passes. I would not be surprised if you found the opposite to be the case on some versions of PHP and/or in a different context.
isset itself is covered by three different op-codes in the VM depending upon the context:
"Simple" Compiled Variables like your example: ZEND_ISSET_ISEMPTY_VAR
Arrays: ZEND_ISSET_ISEMPTY_DIM_OBJ (requires 2 operands, the var and the index)
Object properties: ZEND_ISSET_ISEMPTY_PROP_OBJ (also 2 operands, var and prop name)
It's an interesting question for curiosity's sake but we're in hair splitting territory and it's probably not a real-world optimization strategy.

Categories