如何在 PHP 中将变量重置为 NULL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1854288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reset a variable to NULL in PHP?
提问by TheFlash
I can use isset($var)to check if the variable is not defined or null. (eg. checking if a session variable has been set before)
我可以isset($var)用来检查变量是否未定义或为空。(例如,检查之前是否设置了会话变量)
But after setting a variable, how do I reset it to the default such that isset($var)returns false?
但是在设置变量后,如何将其重置为默认值以便isset($var)返回false?
回答by nacmartin
Use unset($var);
用 unset($var);
回答by nickf
As nacmartin said, unsetwill "undefine" a variable. You could also set the variable to null, however this is how the two approaches differ:
正如 nacmartin 所说,unset将“取消定义”一个变量。您也可以将变量设置为 null,但这就是两种方法的不同之处:
$x = 3; $y = 4;
isset($x); // true;
isset($y); // true;
$x = null;
unset($y);
isset($x); // false
isset($y); // false
echo $x; // null
echo $y; // PHP Notice (y not defined)
回答by mauris
Further explanation:
进一步解释:
While a variable can be null or not null, a variable can also be said to be set or not set.
虽然变量可以为空或不为空,但也可以说变量已设置或未设置。
to set a variable to null, you simply
要将变量设置为 null,您只需
$var = null;
This will make $varnull, equivalent to false, 0and so on. You will still be able to get the variable from $GLOBALS['var']since it is still defined / set. However, to remove a variable from the global and/or local namespace, you use the
这将使$varnull,等价于false,0等等。您仍然可以从中获取变量,$GLOBALS['var']因为它仍然是定义/设置的。但是,要从全局和/或本地命名空间中删除变量,您可以使用
unset($var);
This will make $varnot set at all. You won't be able to find in $GLOBALS.
这将使$var根本没有设置。您将无法在$GLOBALS.
回答by leepowers
Also, you can set the variable to null:
此外,您可以将变量设置为null:
<?php
$v= 'string';
var_dump(isset($v));
$v= null;
var_dump(isset($v));
?>
回答by Gregory Neely
As of php 7.2 directly setting a variable is depreciated. You should not use it in this fashion you should look into using unset instead. https://www.php.net/manual/en/language.types.null.php
从 php 7.2 开始,直接设置变量是折旧的。您不应该以这种方式使用它,而应该考虑使用 unset。https://www.php.net/manual/en/language.types.null.php
unset($v);will result in the same false when checking to see if the variable is null or unset.
unset($v);检查变量是否为空或未设置时将导致相同的错误。
isset($v) === false
is_null($v) === false

