differences in using equality operator in php

Go To StackoverFlow.com

0

can anybody tell me the difference of using '===' as

if (null === $this->getName())

and

if ($this->getName() === null )

if $this->getName is already defined.

thanks in advance

2012-04-04 05:52
by Arun Killu
The variables are switched, and the second one has a space before the close parenthesis - Dustin Graham 2012-04-04 05:53
The first one is a means simply to get the comparison value visible - helps the developer parse the meaning of the code quickly, which is helpful on longer lines - halfer 2012-04-04 05:59


0

There is no difference between the two conditionals, however, it is a common practice to place the value you are checking first, so you don't accidentally turn a conditional check into an assignment operation:

// Conditional
if ($this->getName() === null )

// Assignment
if ($myName = null )

// Avoids the confusion of either the above
if (null === $this->getName())

You can also use the is_null PHP function for testing if variables are null.

2012-04-04 05:57
by Mike Purcell


1

There is no difference as long as you are using === or ==.

Now you might wonder why someone written all their values at left side. This is because we devs tend to forget or have typo writing == and we type =. This is makes accidental assignment.

if($id=13){
  echo "foo";
}

Its hard to find the problem in above code. Which should have been written as $id==13. Those who writes as 13==$id doesn't have to deal with the issue becase when they forget a = it becomes 13=$id which is a syntax error. This way such almost impossible to detect errors are avoided.

2012-04-04 06:03
by Shiplu Mokaddim


0

The === operator in PHP is symmetric, so those are identical.

2012-04-04 05:55
by A B


0

From what I've read, the only notable difference is strictly in the order of writing, enabling an easier following of given tests in some cases.

I also consider PHP evaluating first term first, but this won't be producing any difference since they will both be evaluated anyway.

2012-04-04 05:58
by Victor Nițu
Ads