|
Posted by Daniel Tryba on 07/06/05 17:57
In comp.lang.php steve <a@b.com> wrote:
> | I am looking for something like defined(CONSTANT) but I guess not..
>
> what?
>
> you're crossing my wires. are you trying to define a constant or work with
> variable scope? why not just post your code that's giving you fits. i'd be
> willing to bet that the problem is not with either constants or globals.
> but, that's just me.
No no, Steve was asking an existentialistic question:
How to check if a variable is set?
isset() is not the answer to the question, easily demonstrated with a
little script which outputs:
$ php4 ./huh.php
isset(foo): false, isset(bar): false
Notice: Undefined variable: bar in /tmp/huh.php on line 8
foo: [], bar: []
Both $foo and $bar aren't set (according ot isset()), using them anyway
results in an undefined notice for $bar only. So $foo is defined. But
defined() is for contants only.
So the question remains how to findout if a variable is set. A
workaround for variables in the global scope exists by checking for the
key in the $GLOBALS array:
keyexists(foo): true, keyexists(bar): false
But how can this check be computed for variables in any other scope?
My sample code:
<?php
error_reporting(E_ALL);
$foo=null;
echo "isset(foo): ".(isset($foo)?"true":"false").", isset(bar): ".(isset($bar)?"true":"false")."\n";
echo "foo: [$foo], bar: [$bar]\n";
echo "keyexists(foo): ".(array_key_exists('foo',$GLOBALS)?"true":"false").", keyexists(bar): ".(array_key_exists('bar',$GLOBALS)?"true":"false")."\n";
?>
[Back to original message]
|