如果我正确理解 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() 是否有意义?抛出异常的唯一方法是满足 if (true && true)。
最佳答案
发件人:http://www.php.net/manual/en/language.types.null.php
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().
<?php
if(is_null($obj)){
echo 'is null';
}
虽然 $obj
被认为是 NULL 因为它还没有被注册,它仍然会抛出一个 Notice: undefined ...
if
语句的正确用法应首先检查变量是否存在,然后检查它是否为数组。
if (!isset($required) || !is_array($required)) {}
-或-
if (empty($required) || !is_array($required)) {}
is_array()
的好处是如果 $required
IS NULL 那么它就不是一个数组并且会通过 if 子句。
isset()
和 empty()
都将确保变量存在。未能通过这些方法中的任何一个都将退出 if 语句,并且不会返回任何错误。
关于php - 使用 !is_null() 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21292730/