2015-02-23 46 views
-1

我的問題是,與此代碼我得到3,但因爲它在我看來我應該得到1,但只是不知道如何解決它。運營商的'+ ='表現怪異

示例代碼:

$counter = 0; 
if (($counter = test2() !== false)) { 
    $counter += 2; 
    print $counter; 
} 

function test2() { 
    return -1; 
} 

輸出:3

如果我做的其他方式,它工作正常,我會得到-1。 有人可以告訴我我做錯了什麼。

示例代碼:

$counter = 0; 
if (($counter = test2() !== false)) { 
    $counter -= 2; 
    print $counter; 
} 

function test2() { 
    return 1; 
} 

輸出:1

我希望有人能解釋這個給我,因爲對我來說這是完全不可思議。

+3

在條件檢查執行的任務是著名的壞主意,正是這種原因。 (就可讀和可執行的代碼而言,'!== false'並不能幫助...) – David 2015-02-23 20:43:14

+0

運算符優先級:http://php.net/manual/en/language.operators.precedence.php'!= ='比'='更緊密 – 2015-02-23 20:43:40

回答

2

PHP對待這個喜歡:

$counter = 0; 
if ($counter = (test2() !== false)) { //see? 
    //so counter is equal to 1 
    $counter += 2; 
    print $counter; 
} 

function test2() { 
    return -1; 
} 

這種方式較好:

$counter = 0; 
if (($counter = test2()) !== false) { //see? 
    //now counter is -1 
    $counter += 2; 
    print $counter; 
} 

function test2() { 
    return -1; 
}