0

I would like to test if a variable exists This variable can be set to null.

Is there a function can test that?

isset() returns false if the variable exists but defined to null. I can't use is_null() if my $var is not defined.

Edit: my var is an object property so I did this:

property_exists($pData, $key)

and that works

Thx

Paul
  • 1,290
  • 6
  • 24
  • 46
  • Nope! There is no built-in function aimed for that specific requirement. – felipsmartins Jan 11 '18 at 16:04
  • There is no built-in function to check is variable exists in PHP. [`isset()`](http://php.net/manual/en/function.isset.php) is proper way to check is variable is set or exists. There is also [`defined()`](http://php.net/manual/en/function.defined.php) function which work only for contasts. See also this [question](https://stackoverflow.com/questions/30191521/php-check-if-variable-is-undefined) – Andriy Sushchyk Jan 11 '18 at 16:06
  • 1
    `isset(get_defined_vars()['var'])` will work in global scope or in method function scope. – AbraCadaver Jan 11 '18 at 16:23
  • my var is an object property so I did this: `property_exists($pData, $key)` and it works – Paul Jan 11 '18 at 16:32

1 Answers1

1

I don't think you can - and you probably shouldn't. However, if you aren't using methods you can check the global scope:

$x = null;

var_dump(array_key_exists('x', $GLOBALS)); # true
var_dump(array_key_exists('y', $GLOBALS)); # false

See also https://3v4l.org/Sl8Wi

Sjon
  • 4,989
  • 6
  • 28
  • 46