php最佳實務----檢測一個值是否為null或false

來源:互聯網
上載者:User
使用===操作符來檢測null和布爾false值。

PHP寬鬆的類型系統提供了許多不同的方法來檢測一個變數的值。然而這也造成了很多問題。 使用==來檢測一個值是否為null或false,如果該值實際上是一個Null 字元串或0,也會誤判 為false。isset是檢測一個變數是否有值, 而不是檢測該值是否為null或false,因此在這裡使用是不恰當的。

is_null()函數能準確地檢測一個值 是否為null,is_bool可以檢測一個值 是否是布爾值(比如false),但存在一個更好的選擇:===操作符。===檢測兩個值是否同一, 這不同於PHP寬鬆類型世界裡的相等。它也比is_null()和is_bool()要快一些,並且有些人 認為這比使用函數來做比較更乾淨些。

樣本

<?php$x = 0;$y = null;// Is $x null?if($x == null)    print('Oops! $x is 0, not null!');// Is $y null?if(is_null($y))    print('Great, but could be faster.');if($y === null)    print('Perfect!');// Does the string abc contain the character a?if(strpos('abc', 'a'))    // GOTCHA!  strpos returns 0, indicating it wishes to return the position of the first character.    // But PHP interpretes 0 as false, so we never reach this print statement!    print('Found it!');//Solution: use !== (the opposite of ===) to see if strpos() returns 0, or boolean false.   if(strpos('abc', 'a') !== false)    print('Found it for real this time!');?>

陷阱 測試一個返回0或布爾false的函數的傳回值時,如strpos(),始終使用===和!==,否則 你就會碰到問題。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.