note 52743 added to function.isset
| From: | AndrewPenry at osu1 dot php dot net | Date: | Wed, 11 May 2005 15:17:42 +0000 |
| Subject: | note 52743 added to function.isset | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-89262@lists.php.net to get a copy of this message | ||
The following is an example of how to test if a variable is set, whether or not it is NULL. It makes
use of the fact that an unset variable will throw an E_NOTICE error, but one initialized as NULL
will not.
<?php
function var_exists($var){
if (empty($GLOBALS['var_exists_err'])) {
return true;
} else {
unset($GLOBALS['var_exists_err']);
return false;
}
}
function var_existsHandler($errno, $errstr, $errfile, $errline) {
$GLOBALS['var_exists_err'] = true;
}
$l = NULL;
set_error_handler("var_existsHandler", E_NOTICE);
echo (var_exists($l)) ? "True " : "False ";
echo (var_exists($k)) ? "True " : "False ";
restore_error_handler();
?>
Outputs:
True False
The problem is, the set_error_handler and restore_error_handler calls can not be inside the
function, which means you need 2 extra lines of code every time you are testing. And if you have any
E_NOTICE errors caused by other code between the set_error_handler and restore_error_handler they
will not be dealt with properly. One solution:
<?php
function var_exists($var){
if (empty($GLOBALS['var_exists_err'])) {
return true;
} else {
unset($GLOBALS['var_exists_err']);
return false;
}
}
function var_existsHandler($errno, $errstr, $errfile, $errline) {
$filearr = file($errfile);
if (strpos($filearr[$errline-1], 'var_exists') !== false) {
$GLOBALS['var_exists_err'] = true;
return true;
} else {
return false;
}
}
$l = NULL;
set_error_handler("var_existsHandler", E_NOTICE);
echo (var_exists($l)) ? "True " : "False ";
echo (var_exists($k)) ? "True " : "False ";
is_null($j);
restore_error_handler();
?>
Outputs:
True False
Notice: Undefined variable: j in filename.php on line 26
This will make the handler only handle var_exists, but it adds a lot of overhead. Everytime an
E_NOTICE error happens, the file it originated from will be loaded into an array.
----
Manual Page -- http://www.php.net/manual/en/function.isset.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+52743
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52743&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52743&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52743&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52743&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52743&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+52743&report=yes
Search -- http://master.php.net/manage/user-notes.php