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

好久不见. 提交于 2019-12-01 18:31:58

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.

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