2017-02-09 83 views
0

有一個有趣的問題。在一些遺留代碼中,我們有以下語句。

if (empty($result['email_address']) && empty($result['mobile_number'])) { 
    $token = ''; 
} else { 
    $tokenFinder = new TokenFinder(); 
    $tokenFinder->setEmailAddress($result['email_address']); 
    $tokenFinder->setMobileNumber($result['mobile_number']); 
    $token = $tokenFinder->generate(); 
} 

令牌取景器中的相關內容如下所示:

class TokenFinder{ 

    public function setEmailAddress($email) { 
     $this->email = $email; 
    } 

    public function setMobileNumber($mobile) { 
     $this->mobile = $mobile; 
    } 

    public function generate(){ 
     if ($this->email == '' && $this->mobile == ''){ 
      Throw new Exception('TokenFinder: You cannot fetch a token with no email or mobile number'); 
     } 

昨天,有史以來第一次,在generate()方法異常被觸發。我通過這段代碼運行了失敗消息中的所有收件人,並且異常不會觸發。自拋出Exception以來數據沒有改變。這是一個奇怪的。

有誰知道任何會導致empty($var)評估爲false的值,並且$var == ''將評估爲true。

+2

http://stackoverflow.com/questions/25100890/in-php-why-empty0-returns-true – fizzi

+1

這樣的問題很好的例子,爲什麼總是使用'==='而不是'=='像PHP和JavaScript等語言,以確保您檢查嚴格的平等。 – Simba

+1

可能重複[在PHP中,爲什麼空(「0」)返回true?](http://stackoverflow.com/questions/25100890/in-php-why-empty0-returns-true) – DarkBee

回答

1

empty()返回true在的情況下:

  • 空字符串
  • 0整數
  • 0.0浮子
  • 0作爲字符串
  • 空數組
  • 空可變

(見http://php.net/empty

誤差必須位於php的棘手類型雜耍。可能是,$result['email_address']$result['mobile_numer']包含一個對象,其中__toString實現返回一個空字符串。 emtpy將看到一個對象,== ''看到一個空字符串。

雖然可能有幾十個其他案例。所以你最好的辦法是擺脫邏輯重複(if語句),並在TokenFinder(如isDataValid)中實現一個靜態方法,並用它來檢查類之外的數組。

+0

感謝您的建議。我同意代碼需要在這個領域重新工作。它在我們的待辦事項清單上。感謝您的建議以及對象的想法。我不認爲這是真正的問題,但它肯定有助於提出其他類似的情況。 –

-1

PHP手冊:

空()如果變種存在,並且有一個非空的,非零值 返回FALSE。否則返回TRUE。

相關問題