鑑於下面的表達式:省略三元運算符的第二部分
$att['menutext'] = isset($attrib_in['i_menu_text']) ? : $this->getID();
如果評估爲真,將$att['menutext']
被設置爲true
或$this->getID()
?
鑑於下面的表達式:省略三元運算符的第二部分
$att['menutext'] = isset($attrib_in['i_menu_text']) ? : $this->getID();
如果評估爲真,將$att['menutext']
被設置爲true
或$this->getID()
?
這只是一樣以下
$att['menutext'] = isset($attrib_in['i_menu_text']) ? true : $this->getID();
這將不執行,這是無效的語法PHP < 5.3。
Parse error: syntax error, unexpected ':' on line X
如果你想要的值設置爲true,則使用真:
$att['menutext'] = isset($attrib_in['i_menu_text']) ? true : $this->getID();
或者,它更可能是你想要的:
$att['menutext'] = isset($attrib_in['i_menu_text']) ? $attrib_in['i_menu_text'] : $this->getID();
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
多數民衆贊成在聰明,謝謝 –
之前從來沒有測試,但是它很容易測試:
<?php var_dump(TRUE ? : 'F'); ?>
和說:布爾(真)
是,在版5.3+中間表達式是可選的,返回true。
$a = (true ? : 1); // $a evaluates to true.
$a = (false ? : 1); // $a evaluates to 1.
只是爲了澄清路人,ternery操作符的這個快捷方式版本返回任何條件的評估,不僅在每個實例布爾「真」。在這種情況下,條件將評估爲「真實」。但是如果你有'$ foo = 42? :false;','$ foo'將被分配'42'。 – Wiseguy
有沒有辦法使用第一個表達式作爲第二個或第三個的結果?像'$ db-> get('id','users','id',$ id)? previous_query:anything_else'。現在你必須編寫'$ db-> get('id','users','id',$ id)? $ db-> get('id','users','id',$ id):anything_else'。這使得兩個請求數據庫。在此之前你可以將它保存爲變量,但這並不是我的意思。不可能? –
這不會執行,它是無效的語法。 '解析錯誤:語法錯誤,意外':'在X行上' – nickb
不在PHP 5.3中。 http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary –
這解釋了爲什麼它沒有在5.2.5 :) – nickb