Ternary statement without middle expression

How to replace this :

if( $this->getInfo() ){
   $value = $this->getInfo();
}else{
   $value = $this->getAnotherInfo();
}

This would be nicer solution :

$value = $this->getInfo() ? $this->getInfo() : $this->getAnotherInfo();

But we repeat $this->getInfo() .


这是乐趣:

$value = $this->getInfo() ? : $this->getAnotherInfo();

如果它困扰你不得不重复表达式,你可以编写一个返回第一个真值的函数。

$value = which ($this->getInfo(), $this->getAnotherInfo());

function which () { 
    if (func_num_args()<1) return false;
    foreach (func_get_args() as $s) if ($s) return $s;
    return false;
}

A nasty option would be this:

if (!($value = $this->getInfo())) $value = $this->getOtherInfo();

If the assignment returns false assign the other value.

But aside from this looking disgusting, it is still repetitive, albeit in a different way.


As of PHP 5.3, you can leave out the middle part of the ternary operator and avoid the repetition:

$value = $this->getInfo() ? : $this->getOtherInfo();

Which does what you want.

链接地址: http://www.djcxy.com/p/57728.html

上一篇: 短版$ x? $ x:$ y表达式

下一篇: 没有中间表达的三元陈述