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

随声附和 提交于 2019-12-01 20:52:24

问题


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?


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/11015296/whats-the-meaning-of-the-reverse-entry-null-value-when-checking-the-valu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!