简体   繁体   中英

PHP: How to check if a var has been initiliazed? isset returns false when the var has been set to NULL

<?php
    $var = NULL;

    var_dump(isset($var)); // bool(false)
    var_dump(isset($unset_var)); // bool(false)
?>

isset($var) should return TRUE, since it has been set to NULL.

Is there any way to check for this?

Thanks!

use get_defined_vars() to get an array of the variables defined in the current scope and then test against it with array_key_exists();

Edited:

if you wanted a function to test existence you would create one like so:

function varDefined($name,$scope) {
  return array_key_exists($name, $scope);
}

and use like so in any given scope:

$exists = varDefined('foo',get_defined_vars());

Should work for any scope.

Not very pretty, but...

array_key_exists('var', $GLOBALS);

(You can't use @is_null($var) , because it evaluates to true either way [and it's not really good practice to suppress errors using the @ operator...])

if it's in global scope, you can try checking if the key exists in the $GLOBALS superglobal (using array_key_exists()).

but you're probably doing something wrong if you need to know this :)

如果是全球性的,则可以执行以下操作:

if(array_key_exists('var', $GLOBALS))

Any unset var will evaluate to null:

php > $a = null;
php > var_dump($a === null);
bool(true)
php > var_dump($a === $b);
bool(true)

(using interactive console - php -a )

Aren't variables initialized to NULL by default? So, there isn't really a difference between one that hasn't been inited and one that you've set to NULL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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