2013-01-01 23 views
2

我有以下代碼snipplet:列表(),如果和短路評價

$active_from = '31-12-2009'; 
if(list($day, $month, $year) = explode('-', $active_from) 
    && !checkdate($month, $day, $year)) { 
    echo 'test'; 
} 

爲什麼我得到一個未定義的變量錯誤?

list($day, $month, $year) = explode('-', $active_from)返回true,所以list()被評估,不是嗎?我認爲,應該定義變量?我要監督什麼?

這並不在我看來相同,不引發錯誤:

$active_from = '31-12-2009'; 
list($day, $month, $year) = explode('-', $active_from); 
if(checkdate($month, $day, $year)) { 
    echo 'test'; 
} 

這引發任何錯誤:

if((list($day, $month, $year) = explode('-', $active_from)) && checkdate($month, $day, $year)) { 

但我真的不明白,爲什麼:-)

感謝您的解釋

+2

這裏沒有錯誤http://codepad.org/33BV3EsO –

回答

3

這是operator precedence一個問題,在你的情況下,&&=前評估,導致您所描述的錯誤。

您可以通過將賦值語句放在圓括號中來解決此問題。

明確,你的代碼應該閱讀

if( (list($day, $month, $year) = explode('-', $active_from)) 
    && !checkdate($month, $day, $year)) { 

請注意,我已經改變了它從if($a=$b && $c)if(($a=$b) && $c)。圓括號強制賦值運算符(=)在結合(&&)之前進行評估,這正是您想要的。

+0

非常感謝你:) –

+0

沒問題,@FabianBlechschmidt。 (新年快樂 ;-) ) – Richard

1

閱讀關於operator precedence

if (list($day, $month, $year) = explode('-', $active_from) && !checkdate($month, $day, $year)) { 

是相同的

if (list($day, $month, $year) = (explode('-', $active_from) && !checkdate($month, $day, $year))) { 
+0

非常感謝你:) –