开发者

How to know if a PHP variable exists, even if its value is NULL?

开发者 https://www.devze.com 2023-04-10 22:55 出处:网络
$a = NULL; $c = 1; var_dump(isset($a)); // bool(false) var_dump(isset($b)); // bool(false) var_dump(isset($c)); // bool(true)
$a = NULL;
$c = 1;
var_dump(isset($a)); // bool(false)
var_dump(isset($b)); // bool(false)
var_dump(isset($c)); // bool(true)

How can I distinguish $a, which exists 开发者_开发知识库but has a value of NULL, from the “really non-existent” $b?


Use the following:

$a = NULL;
var_dump(true === array_key_exists('a', get_defined_vars()));


It would be interesting to know why you want to do this, but in any event, it is possible:

Use get_defined_vars, which will contain an entry for defined variables in the current scope, including those with NULL values. Here's an example of its use

function test()
{
    $a=1;
    $b=null;

    //what is defined in the current scope?
    $defined= get_defined_vars();

    //take a look...
    var_dump($defined);

    //here's how you could test for $b
    $is_b_defined = array_key_exists('b', $defined);
}

test();

This displays

array(2) {
  ["a"] => int(1)
  ["b"] => NULL
}
0

精彩评论

暂无评论...
验证码 换一张
取 消