How to prevent PHP Notices with a defined variable?
Basicly I have a bunch of links on a page and I will use something like this
<?PHP echo $SITE_PATH ?>
Many many times on the same page but it will show a Notice in PHP f开发者_开发知识库or doing so.
I know you are supposed to use things like isset() but would I really need to use it every time I call?
<?PHP echo $SITE_PATH ?>
--- EDIT :
If I switch to using a defined variable, then the notices seem to go awayTwo solutions, here :
- only use variables that exist -- which is what you should probably do.
- or test if they exist (with
isset
) before trying to use them.
There is no magic ^^
If your application is using many not-set variables, you probably have some problem in your design.
In a case such as the one you presented, for a variable that's used lots of times, I would make sure it exists, and, if not, set it to '', for instance, at the beginning of my script.
That's not really looking great, but it'll work -- and, this way, you won't have to go through your whole application, patching everything.
(Or I might also disable the E_NOTICE
error_reporting
level -- I don't like that idea, but, sometimes, it's really the only way to deal with some code base)
You can supress messages by using @:
print @$site_path;
Or you can use a ternary operation to get a default value:
print (isset($site_path)) ? $site_path : "default_path" ;
In the end though, you shouldn't be using variables that aren't set. If you are, you need to re-think your approach. Handle this information up-front, so the rest of your scripts can run without problems like this.
You really should make sure a variable is set before using it (especially echoing it to the page). If the variable is coming from an insecure source ($_GET, $_POST, database) then you should do some type of filtering to prevent a security breach (cross site scripting (XSS), cross site request forgery (CSRF), etc...) but if you feel like everything is safe and you just don't want to show errors (e.g. in production) set your error reporting to 0.
E.g. error_reporting(0);
You can do this at the php.ini level or per page (set error_reporting(0);
at the top of the page).
On a side note, when in production you don't ever want to display errors. Log them instead. In development you want to see all of your errors (E_STRICT).
You could create a function to check if the variable is set and return it:
function EchoVar() {
global $SITE_PATH;
return isset($SITE_PATH) ? $SITE_PATH : '';
}
// calling it
echo EchoVar();
精彩评论