已设置 vs 空 vs is_null

php
2022-08-30 14:28:53

我正在尝试编写一个脚本,当用户上传文件并且不输入名称时,将返回错误。我尝试过使用is_null,空和isset,但它们都不起作用。例如,在下面,即使输入了名称,is_null也会返回错误。任何人都可以帮忙吗?

$caption = $_REQUEST[$name_input_name];

if(is_null($caption)) {
    $file->error = 'Please Enter a Title';
    return false;
}

答案 1

is_null()如果未设置变量,则发出警告,但未设置。isset()empty()

$a - variable with not null value (e.g. TRUE)
$b - variable with null value. `$b = null;`
$c - not declared variable
$d - variable with value that cast to FALSE (e.g. empty string, FALSE or empty array)
$e - variable declared, but without any value assigned
$a->a - declared, but not assigned object property. (`public $a;`)
A::$a - declared, but not assigned static class property.

         |   $a  |   $b  |   $c  |   $d  |   $e  | $a->a | A::$a |
---------+-------+-------+-------+-------+-------+-------+-------+
is_null()| FALSE | TRUE  |TRUE*W | FALSE | TRUE*W| TRUE  | TRUE  |
---------+-------+-------+-------+-------+-------+-------+-------+
isset()  | TRUE  | FALSE | FALSE | TRUE  | FALSE | FALSE | FALSE |
---------+-------+-------+-------+-------+-------+-------+-------+
empty()  | FALSE | TRUE  | TRUE  | TRUE  | TRUE  | TRUE  | TRUE  |
---------+-------+-------+-------+-------+-------+-------+-------+
null === | FALSE | TRUE  |TRUE*W | FALSE | TRUE*W| TRUE  | TRUE  |
---------+-------+-------+-------+-------+-------+-------+-------+
null ==  | FALSE | TRUE  |TRUE*W | TRUE  | TRUE*W| TRUE  | TRUE  |
---------+-------+-------+-------+-------+-------+-------+-------+

TRUE*W - function return TRUE, but same time emits WARNING.

empty() 函数文档页面上,您可以阅读:

以下内容被视为空:

....

$var;(已声明但未带值的变量)

代码定义变量,但没有为其赋值,但这是错误的,这可能会产生误导。变量仍未定义,并且类型识别函数,例如,如果作为参数传递,则发出警告。$var;$varis_null()$var

但它不适用于未解决的类或对象属性。声明它们而不分配某些值会自动分配 NULL。

断续器默认情况下,PHP 7.4 中的类型化属性不按 NULL 分配。如果未对它们设置任何值,则将其视为未分配。

一些低级描述:

isset()并且是核心函数,将根据zval类型直接编译为特定的操作码:empty()

ZEND_ISSET_ISEMPTY_THIS
ZEND_ISSET_ISEMPTY_CV
ZEND_ISSET_ISEMPTY_VAR
ZEND_ISSET_ISEMPTY_DIM_OBJ
ZEND_ISSET_ISEMPTY_PROP_OBJ
ZEND_ISSET_ISEMPTY_STATIC_PROP

此外,它们将通过相同的函数进行编译zend_compile_isset_or_empty

函数是类型识别器函数,如 、 、 等。并且将像用户定义的函数一样调用操作码等。is_null()is_numericis_recourceis_boolINIT_FCALL_BY_NAME/DO_FCALL_BY_NAME

/* {{{ proto bool is_null(mixed var)
   Returns true if variable is null
   Warning: This function is special-cased by zend_compile.c and so is usually bypassed */
PHP_FUNCTION(is_null)
{
    php_is_type(INTERNAL_FUNCTION_PARAM_PASSTHRU, IS_NULL);
}

答案 2

isset()将检查变量是否已设置,即

<?php

echo isset($var); // false

$var = 'hello';

empty()将检查变量是否为空,即

<?php

$emptyString = '';

echo empty($emptyString); // true

is_null()将检查哪个与空不同,因为它设置为不是空字符串。(NULL 可能是一个令人困惑的概念)NULLNULL

由于您的标题是字符串,我认为您希望使用empty()

if (!isset($_REQUEST[$name_input_name]) || empty($_REQUEST[$name_input_name])) {
    $file->error = 'Please Enter a Title';
    return false;
}

推荐