if(null) php_php-使用!is_null()的正确方法

标签:php

如果我正确理解is_null,则PHP面向对象解决方案中有一个似乎有缺陷的示例.

本书中的示例代码如下:

if (!is_null($required) && !is_array($required)) {

throw new Exception('The names of required fields must be an array, even if only one field is required.');

}

这段代码应该用来测试var $required不是NULL而是一个数组.据我了解,如果未设置变量或为NULL,则is_null()返回TRUE.因此,在该示例中,如果您试图在未设置变量,NULL或不是数组的情况下引发异常,则否定is_null()是否有意义?引发异常的唯一方法是满足(true&& true).

解决方法:

A variable is considered to be null if:

it has been assigned the constant NULL.

it has not been set to any value yet.

it has been unset().

if(is_null($obj)){

echo 'is null';

}

虽然$obj因为尚未注册而被认为是NULL,但它仍会引发一个通知:undefined …

if语句的正确用法应首先检查该变量是否存在,然后检查该变量是否为数组.

if(!isset($required)||!is_array($required)){}

-要么-

if(空($required)||!is_array($required)){}

is_array()的好处是,如果$required为NULL,则它不是数组,并且将传递if子句.

isset()和empty()都将确保该变量存在.不通过这些方法中的任何一个将退出if语句,并且不会返回任何错误.

标签:php

来源: https://codeday.me/bug/20191030/1964090.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值