Home  >  Article  >  Backend Development  >  关于 PHP Boolean 的细节

关于 PHP Boolean 的细节

WBOY
WBOYOriginal
2016-06-23 13:52:40909browse

最近比较喜欢抠细节,因为这些细节对于代码的编写以及bug 查找非常有帮助,能够很大程度上提高项目的开发速度.

废话少说,我们开始讲解 php Boolean.

首先,boolean 型是 php的基本数据类型, 它要么是true,或者false. 大小写不区分.

如果需要将其他类型转换为bool类型的时候, 可以使用(bool) 或者(boolean),(Boolean)进行转换.

echo true === (bool)-1;echo true === (boolean)-1;echo true === (Boolean)-1;

	public function test_true () {		$this->assertTrue(-1 == true); //-1	=> true		$this->assertTrue("false" == true); //"false" => true		$this->assertTrue("null" == true);  //"null"  => true		$this->assertTrue("0.0" == true);   //"0.0"   => true		$this->assertTrue((bool)-1);		$this->assertTrue((boolean)-1);		$this->assertTrue((Boolean)-1);	}	public function test_false () {		$this->assertTrue (null == false);//null => false		$this->assertTrue (0 == false);   //0	 => false		$this->assertTrue (0.0 == false); //0.0	 => false		$this->assertTrue ("" == false);  //""	 => false		$this->assertFalse (" " == false); //" " => true	}

以上是我写的两个简单的测试用例. 全部都断言成功.

-1 ==  true 结果为true. 

同理 null == false 结果也为true .

就是非严格的类型比对.

还有要注意搞清楚 bool , boolean , Boolean . 其实应该是没有太大区别的. 但是始终要记住, 它只是基本的数据类型,并没有什么类的概念...



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn