Undefined Variable Error Message PHP

时间:2018-02-03 07:55:27

标签: php

I have a function named categories_name() which is given below:

function categories_name(){
    if($GLOBALS["pro_cat"] == "1"){
        $name_cat = "<a href='category.php cat_id=".$GLOBALS["pro_cat"]."'>Laptops</a>";
    }else if($GLOBALS["pro_cat"] == "2"){
        $name_cat = "<a href='category.php?cat_id=".$GLOBALS["pro_cat"]."'>Tablets</a>";
    }else if($GLOBALS["pro_cat"] == "3"){
        $name_cat = "<a href='category.php?cat_id=".$GLOBALS["pro_cat"]."'>Mobile Phones</a>";
    }else{
        echo "Not defined";
    }
    return $name_cat;
}

It basically returns the value of $name_cat.

But when I run this program I get this error:

Undefined variable: name_cat on line 2

Which supposed to be this:

return $name_cat;

2 个答案:

答案 0 :(得分:1)

you could also shorten your code. I see only the Label of the link gets changed.

Do this

function categories_name() {    
$link_title = '';
if ($GLOBALS["pro_cat"] == "1") {
    $link_title = 'Laptops';
} else if ($GLOBALS["pro_cat"] == "2") {
    $link_title = 'Tablets';
} else if ($GLOBALS["pro_cat"] == "3") {
    $link_title = 'Mobile Phones';
} else {
    $link_title = 'Undefined';
}
return "<a href='category.php?cat_id=" . $GLOBALS["pro_cat"] . "'>" . $link_title . "</a>";
}

答案 1 :(得分:0)

This is not an error. This is s notice. Becouse you want to get non definded variable value php interpreter notice that the variabli is not definde. Try ad this to the beginning if you didn't want to get this notice:

error_reporting(E_ALL ^ E_NOTICE);