标签: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