Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:使用简短的if语句而不使用else?_Php_If Statement_Ternary Operator - Fatal编程技术网

PHP:使用简短的if语句而不使用else?

PHP:使用简短的if语句而不使用else?,php,if-statement,ternary-operator,Php,If Statement,Ternary Operator,我是短if版本的粉丝,例如: ($thisVar == $thatVar ? doThis() : doThat()); ($thisVar == $thatVar ? doThis()); 不过,我想删掉else语句,例如: ($thisVar == $thatVar ? doThis() : doThat()); ($thisVar == $thatVar ? doThis()); 然而,这是行不通的。有没有什么方法是我遗漏的呢?三元运算符被设计为产生两个值中的一个。它是一个表达式,

我是短if版本的粉丝,例如:

($thisVar == $thatVar ? doThis() : doThat());
($thisVar == $thatVar ? doThis());
不过,我想删掉else语句,例如:

($thisVar == $thatVar ? doThis() : doThat());
($thisVar == $thatVar ? doThis());

然而,这是行不通的。有没有什么方法是我遗漏的呢?

三元运算符被设计为产生两个值中的一个。它是一个表达式,而不是一个语句,您不应该将它用作if/else的较短替代

无法省略
部分:如果您这样做,表达式的计算值会是多少


如果调用的方法有副作用,请使用If/else。不要走捷径。可读性比保存几个字符更重要。

如果没有
else
,就不能使用它。但你可以试试这个:

($thisVar != $thatVar ?: doThis());


不,没有办法做到这一点,因为它不是一个简短的
if
,更多的是一个简短的
if/else
(尽管这只是一个非常简单的看待它的方式)
[1,null][$thisVar==$thatVar]??doThis()我不完全同意。想象一下:
@ErikKubica这些表达式没有副作用。