关于 PHP Boolean 的细节

最近比较喜欢抠细节,因为这些细节对于代码的编写以及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 . 其实应该是没有太大区别的. 但是始终要记住, 它只是基本的数据类型,并没有什么类的概念...



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值