简体   繁体   English

php如何判断一个变量是空的还是未定义的

[英]How to tell whether a variable is null or undefined in php

Is there a single function that can be created to tell whether a variable is NULL or undefined in PHP?有没有可以创建告诉变量是否为空或PHP未定义单一的功能? I will pass the variable to the function (by reference if needed) but I won't know the name of the variable until runtime.我会将变量传递给函数(如果需要,通过引用)但直到运行时我才知道变量的名称。

isset() and is_null() do not distinguish between NULL and undefined. isset()is_null()不区分 NULL 和 undefined。
array_key_exists requires you to know the name of the variable as you're writing your code. array_key_exists要求您在编写代码时知道变量的名称。
And I haven't found a way to determine the name of a variable without defining it.而且我还没有找到一种无需定义即可确定变量名称的方法。

Edit编辑

I've also realized that passing a variable by reference automatically defines it.我还意识到通过引用传递变量会自动定义它。

Elaboration细化

Through the collection of these answers and comments I've determined that the short answer to my question is "No".通过收集这些答案和评论,我确定对我的问题的简短回答是“否”。 Thank you for all the input.感谢您的所有投入。

Here are some details on why I needed this:以下是我为什么需要这个的一些细节:

I've created a PHP function called LoadQuery() that pulls a particular SQL query from an array of queries and then prepares it for submission to MySQL.我创建了一个名为LoadQuery()的 PHP 函数,它从一组查询中提取特定的 SQL 查询,然后准备将其提交给 MySQL。 Most-importantly I scan the query for variables (like $UserID ) that I then replace with their values from the current scope.最重要的是,我扫描查询变量(如$UserID ),然后将其替换为当前作用域中的值。 In creating this function I needed a way to determine if a variable had been declared, and was NULL, empty, or had a value.在创建这个函数时,我需要一种方法来确定一个变量是否已被声明,是否为 NULL、空或有值。 This is why I may not know the name of the given variable until runtime.这就是为什么我可能直到运行时才知道给定变量的名称。

Using modified example from PHP - Differenciate an undefined variable from a null variable使用PHP 中的修改示例- 将未定义的变量与空变量区分开来

we can differentiate it:我们可以区分它:

$v1 = null;

echo (isset($v1) ? '$v1 set' : '$v1 not set') . PHP_EOL;
echo (is_null($v1) ? '$v1 null' : '$v1 not null') . PHP_EOL;
echo (empty($v1) ? '$v1 empty' : '$v1 not empty') . PHP_EOL;
echo (array_key_exists('v1', get_defined_vars()) ? '$v1 defined' : '$v1 not defined') . PHP_EOL;

echo PHP_EOL;
echo (isset($v2) ? '$v2 set' : '$v2 not set') . PHP_EOL;
echo (@is_null($v2) ? '$v2 null' : '$v2 not null') . PHP_EOL;
echo (empty($v2) ? '$v2 empty' : '$v2 not empty') . PHP_EOL;
echo (array_key_exists('v2', get_defined_vars()) ? '$v2 defined' : '$v2 not defined') . PHP_EOL;

prints:印刷:

$v1 not set
$v1 null
$v1 empty
$v1 defined

$v2 not set
$v2 null
$v2 empty
$v2 not defined

we can use array_key_exists(..., get_defined_vars()) and is_null(...) to detect both situations我们可以使用array_key_exists(..., get_defined_vars())is_null(...)来检测这两种情况

You can't wrap this kind of logic in a function or method as any variable defined in a function signature will be implicitly "set".您不能将这种逻辑包装在函数或方法中,因为函数签名中定义的任何变量都将被隐式“设置”。 Try something like this (contains code smell)尝试这样的事情(包含代码气味)

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
error_reporting(E_ALL);
set_error_handler("exception_error_handler");

try {
    if (null === $var) {
        // null your variable is, hmmm
    }
} catch (ErrorException $e) {
    // variable is undefined
}

In PHP typically variables that have not been set or that have been unset are considered null .在 PHP 中,通常未设置或未设置的变量被视为null The meaning of null is "no value". null的意思是“没有价值”。 There is a distinct difference between "no value" and a value left blank. “无值”和留空的值之间存在明显区别。 For instance, if a user submitted a form with foo=&bar=baz , $_GET['foo'] is set to the value of empty string "" , which is distinctly different from null which would be the value for any key other than 'foo' and 'bar' .例如,如果用户提交了一个带有foo=&bar=baz的表单, $_GET['foo']被设置为空字符串""的值,这与null明显不同, null是除'foo''bar'

That all being said, you can find out if a variable was never set or unset , although they will always evaluate to true with is_null ( is_null is the negative of isset with the exception that it will throw notices if the value was never set).话虽如此,您可以找出变量是否从未设置或未unset ,尽管它们总是会使用is_null评估为trueis_nullisset的负数,但如果从未设置该值则会抛出通知)。

One way is if you have the variable in an array of some sort:一种方法是,如果您在某种数组中有变量:

echo array_key_exists( $variableName, $theArray ) ? 'variable was set, possibly to null' : 'variable was never set';

If you need to check a global variable, use the $GLOBALS array:如果需要检查全局变量,请使用$GLOBALS数组:

echo array_key_exists( $variableName, $GLOBALS ) ? 'variable exists in global scope' : 'this global variable doesn\'t exist';

The alternative method I've come up with for figuring out whether the variable was set is a bit more involved, and really unnecessary unless this is a feature that you absolutely have to have (in which case you should be able to build it without too much difficulty).我想出的用于确定变量是否设置的替代方法有点复杂,而且真的没有必要,除非这是您绝对必须拥有的功能(在这种情况下,您应该能够在没有太多的情况下构建它难度很大)。

It relies on the fact that is_null triggers a notice when a variable hasn't been set.它依赖于is_null在未设置变量时触发通知的事实。 Add an error handler that converts errors into Exceptions , and use a try...catch... block to catch the exception that's thrown and set a flag in the catch statement.添加一个将errors转换为Exceptions的错误处理程序,并使用try...catch...块来捕获抛出的异常并在catch语句中设置一个标志。 Just after the catch block execute your code that relies on this feature.就在catch块执行依赖此功能的代码之后。

It's a dirty-nasty-hack if you ask me, and completely unnecessary, as null should be considered the same as an unset variable.如果你问我,这是一个肮脏的黑客,完全没有必要,因为null应该被视为与未unset变量相同。

Essentially the answer is no.基本上答案是否定的。 There is not a single function you can create that will tell whether a runtime variable is null or is undefined.您无法创建单个函数来判断运行时变量是 null 还是未定义。 (by 'runtime variable' I mean a variable who's name you don't yet know at the time of coding. See Elaboration in the question above). (“运行时变量”是指在编码时您还不知道其名称的变量。请参阅上述问题中的详细说明)。

Relevant Observations:相关观察:

  • There's no way to retrieve the name of a variable at runtime without giving it a value and hence declaring it.没有办法在运行时检索变量的名称而不给它一个值并因此声明它。
  • If you pass a variable by reference, instead of by value, you're automatically declaring it.如果您通过引用而不是通过值传递变量,则会自动声明它。 So then in the function you can't go back and determine whether it was declared before you passed it.因此,在函数中,您无法返回并确定它是否在传递之前已声明。
  • You can use array_key_exists('variable_name', $GLOBALS) as @zzzzBov stated, to see if a variable has been declared, but only if you know the name of the variable at coding time.您可以使用array_key_exists('variable_name', $GLOBALS)在编码时间@zzzzBov说,看一个变量已经声明,但是只有当你知道这个变量的名称。

Possible 'Dirty' Solutions可能的“脏”解决方案

  • As @Phil (and @zzzzBov) explained you could use a messy trick of capturing error messages that would get thrown when you reference an undeclared variable.正如@Phil(和@zzzzBov)所解释的那样,您可以使用一种凌乱的技巧来捕获在您引用未声明的变量时会抛出的错误消息。

  • I also considered a method where you: Make note of all the keys in $GLOBALS , then store a unique value in your target variable (recording it's original value first for later use).我还考虑了一种方法:记下$GLOBALS的所有键,然后在目标变量中存储一个唯一值(首先记录它的原始值以备后用)。 And then search $GLOBALS looking for that unique value to determine the name of the variable AND (by comparing with your earlier look at $GLOBALS ) determine if the variable existed before.然后搜索$GLOBALS查找该唯一值以确定变量的名称并(通过与您之前查看的$GLOBALS进行比较)确定该变量之前是否存在。 But this also seems messy and unreliable.但这也显得凌乱和不可靠。

您可以使用以下命令获取当前范围内已定义变量的数组:

get_defined_vars();

In PHP 5.2 or greater, I guess it is possible as follows:在 PHP 5.2 或更高版本中,我想可能如下:

// checking a variable (before and after it is defined)
$var_status1 = @is_defined( $variable, __LINE__, __FILE__ ); // don't put any additional code on this line
$variable = NULL;
$var_status2 = @is_defined( $variable, __LINE__, __FILE__ ); // don't put any additional code on this line

function is_defined( $var, $line, $file ) {
    $e = error_get_last();
    if ( $e !== NULL && $e['type'] === 8 && $e['line'] === $line && $e['file'] === $file  ) {
        return 'Undefined';
    } else {
        return 'Defined';
    }
}

echo $var_status1 . '<br>';
echo $var_status2 . '<br>';

Note: I did not have time to test this solution in all possible situations (I just use it in a plugin I developed), so everyone is invited to find a flaw here.注意:我没有时间在所有可能的情况下测试这个解决方案(我只是在我开发的插件中使用它),所以请大家在这里找到一个缺陷。

This only works with globally defined variables.这仅适用于全局定义的变量。 Because of scoping it won't work with local variables in functions or with class properties, but of course it's only one line so you could just copy it into a function.由于作用域,它不适用于函数中的局部变量或类属性,但当然它只有一行,因此您可以将其复制到函数中。

function isNullOrUndefined($variable_name) {
  global $$variable_name;
  if (!isset($$variable_name) || is_null($$variable_name)) {
    return true;
  }
  return false;
}

$foo = "foo";
$bar = null;

isNullOrUndefined("foo") //false
isNullOrUndefined("bar") //true
isNullOrUndefined("baz") //true

what about this?那这个呢?

try {
    $undefined_var
} catch (Exception $ex) {
    $is_undefined = true;
}
if(empty($is_undefined)){ ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM