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() 是否有意义?抛出异常的唯一方法是满足 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/

相关文章:

php - kohana中的继承

php - FedEx Api : Bad Request Error, 参数丢失或重复。请修改您的请求并重试

php - 由于某种原因,存储在 MYSQL 上的文件名是错误的

php - Redis 时间序列数据和时区

php - 使用 jquery ajax 上传多个图像并使用 php 处理它们

php - 脚本在 "504 Gateway Time-out"之后继续执行

php - 通过 PHP 更新 MySQL

php - sql 查询中的输入变量

php - 我可以使用 PHP 随机字符串随机播放获得的不同字符串的数量

php - 使用 $wpdb 在 wordpress 中锁定表