2011-11-11 67 views
9

鑑於下面的表達式:省略三元運算符的第二部分

$att['menutext'] = isset($attrib_in['i_menu_text']) ? : $this->getID(); 

如果評估爲真,將$att['menutext']被設置爲true$this->getID()

+0

這不會執行,它是無效的語法。 '解析錯誤:語法錯誤,意外':'在X行上' – nickb

+0

不在PHP 5.3中。 http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary –

+0

這解釋了爲什麼它沒有在5.2.5 :) – nickb

回答

2

這只是一樣以下

$att['menutext'] = isset($attrib_in['i_menu_text']) ? true : $this->getID();

+10

工作只是爲了澄清對路人,ternery操作符的這個快捷方式版本會返回任何條件評估的結果,而不是每個實例中的布爾值「true」。在這種情況下,條件將評估爲「真實」。但是如果你有'$ foo = 42? :false;','$ foo'將被分配'42'。 – Wiseguy

+0

我的事實,這個答案和註釋實際上回答了這個問題我** **的意思問還有一個我沒** **問 –

+0

這個答案是不正確,沒有'isset'暗示的印象特別深刻。 – chx

0

這將不執行,這是無效的語法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(); 
14

根據this reference

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.

+0

多數民衆贊成在聰明,謝謝 –

1

之前從來沒有測試,但是它很容易測試:

<?php var_dump(TRUE ? : 'F'); ?> 

和說:布爾(真)

2

是,在版5.3+中間表達式是可選的,返回true。

$a = (true ? : 1); // $a evaluates to true. 
$a = (false ? : 1); // $a evaluates to 1. 
+1

只是爲了澄清路人,ternery操作符的這個快捷方式版本返回任何條件的評估,不僅在每個實例布爾「真」。在這種情況下,條件將評估爲「真實」。但是如果你有'$ foo = 42? :false;','$ foo'將被分配'42'。 – Wiseguy

+0

有沒有辦法使用第一個表達式作爲第二個或第三個的結果?像'$ db-> get('id','users','id',$ id)? previous_query:anything_else'。現在你必須編寫'$ db-> get('id','users','id',$ id)? $ db-> get('id','users','id',$ id):anything_else'。這使得兩個請求數據庫。在此之前你可以將它保存爲變量,但這並不是我的意思。不可能? –