php Undefined variable: article_id
I keep getting this as a warning I want to avoid getting this warning when it is undefined without turning warnings off
here is the context
$url_items = array("foo");
$article_id = db_escape($url_item开发者_如何转开发s[1]);
$article = get_article($article_id);
function get_article($article_id = NULL) {.....}
I'm thinking that the easiest way to solve it is like this:
$url_items = array("foo");
$article = empty($url_items[1]) ? get_article() : get_article(db_escape($url_items[1]));
function get_article($article_id = NULL) {.....}
This should works because you give $article_id
a default value in the function. However, you could just as easily change the middle ternary part to null if you don't want to execute at all if there is no $article_id
.
Edit: If you have an article_id 0, you may want to change empty
to !isset
Edit 2: Modified to avoid the undefined offset warning.
You don't say exactly which line is causing the error, but you ought to use isset
for any variables you are not sure exist. For example:
$url_items = array("foo");
if ( isset($url_items[1]) )
{
$article_id = db_escape($url_items[1]);
$article = get_article($article_id);
}
function get_article($article_id = NULL) {.....}
You'll also want to check the content of the db_escape
method, in case that is also doing something with an undefined variable.
One other way around the problem is to pass the variable to the function by reference using &
:
function get_article(&$article_id) {
if ( $article_id == null ) {
// handle null case here
}
else {
// get the article
}
}
put this before your code:
error_reporting(E_ALL ^ E_NOTICE);
PHP Manual: error_reporting
so it was pretty simple after all that and yes maybe I could have phrased my question better, but it still bothers me that there is not a simpler way to do this
if (isset($url_items[1])){
$article_id = db_escape($url_items[1]);
}else{
$article_id = null;
}
$article = get_article($article_id);
I don't know if this is related to the error, but you should know that PHP indexes arrays starting with 0, so the second line should be
$article_id = db_escape($url_items[0]);
Also, it is probably a typo, but the first line should be
var $url_items = array("foo");
i think this would be a nicer way maybe there is a better way but i think just hiding the warning is the wrong way...
$article_id = db_escape($url_items[1]);
if(empty($article_id)){
$article_id = null;
}
edit corrected the code
精彩评论