Page 1 of 1

How can I tell if a variable has been defined?

Posted: Thu Feb 07, 2008 10:40 pm
by gregambrose
Can anyone help me with a problem. It should be simple but I can't work out a solution.

I need to be able to see if a variable is defined, even if its value is null.

You can't use isSet() as it gives false after you set the variable to null as follows.

$a = null
isSet($a) give false, but the variable exists, it just has a null value, Subsequent use of $a in function calls will be fine.

You can't use is_null() as it gets an error when the variable has never been defined.

I hope this makes sense,and that somebody can help

Re: How can I tell if a variable has been defined?

Posted: Thu Feb 07, 2008 10:50 pm
by Christopher
It's ugly, but you could maybe use the error supression operator:

Code: Select all

if (! isSet($a) && ! @is_null($a)) {

Re: How can I tell if a variable has been defined?

Posted: Thu Feb 07, 2008 11:41 pm
by gregambrose
Thanks for the note. The trouble is is_null() returns true on an undefined variable.

In the following, where $test has never been used

if(! isSet($test) && ! @is_null($test)) { echo 'undefined'; } else echo "was defined";

We get the following result

was defined
Notice: Undefined variable: test in C:\Docu......

Not sure why the @ is being disregarded, but that doesn't change the problem.

Re: How can I tell if a variable has been defined?

Posted: Fri Feb 08, 2008 12:20 am
by Christopher
Did you try other combinations and chained if()s ? Like:

Code: Select all

if(! isSet($test) && @is_null($test)) {
} elseif (! isset($a) ) {
...
I think the solution would be of interest to people here...

Re: How can I tell if a variable has been defined?

Posted: Fri Feb 08, 2008 12:50 am
by Kieran Huggins
For sure it is - we could write real_isset() and warn people never to use the legacy isset() function instead of fixing it.

Whoa... deja-vu! :twisted:

Re: How can I tell if a variable has been defined?

Posted: Fri Feb 08, 2008 2:00 am
by gregambrose
I had a reply on this problem from the Sydney PHP Group , Precariouspanther, who came up with the following. Rather ugly but it works.

$a=null;
if(array_key_exists("a",get_defined_vars())){
echo "$a Has been defined or is null";
}

I'll wrap this in a function and add it to my library, even though its not very elegant. You would think PHP would have a function variableDefined() like defined() for constants.

I've tried all combinations of if statements on isSet(), empty() and is_null() (the only relevant functions I think), and can't get a solution.