PHP:如何检查var是否已初始化? 当var设置为NULL时,isset返回false

<?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...])

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 )

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 :)

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.

If it's a global, you can do:

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