PHP shorthand syntax

穿精又带淫゛_ 提交于 2019-12-20 04:17:06

问题


I've just came across this on GitHub.

 ($config === NULL) and $config = Kohana::config('email');

Is that the equivalent of

if ($config === NULL) {
    $config = Kohana::config('email');
}

Is this commonplace? Would I expect other developers looking at my code if I used that first way to instantly know what it was doing?


回答1:


Took me a second to get it, but that should actually work in just about every programming language. Because the "and" or "or" operators are lazily evaluated, if the statement on the left is false, then there's no need to evaluate the rest of the statements because the whole expression will always be false (false and true is false). Likewise, you can do it with "or", but the statement on the left would have to be true, then the one on the right wouldn't be evaluated.

PS: It doesn't really matter in this case that what's on the right isn't really a boolean expression; it'll just take on the truth value of $config




回答2:


AND is a PHP logical operator.

($config === NULL) and $config = Kohana::config('email');

has equivalent outcome (but has a lesser operator precedence) to

($config === NULL) && $config = Kohana::config('email');

Personally, to avoid any confusion I would use your second approach.



来源:https://stackoverflow.com/questions/2475047/php-shorthand-syntax

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