在函数中包含已存在的变量

时间:2012-06-23 02:04:57

标签: php function

我试图创建一个函数,它接受一个输入,确定它的值,并从已包含在脚本中的现有数组中输出一个单词。问题是输出是空白的,我相信函数忽略了脚本中已经存在的变量,是否有办法改变这一点,因此函数不会忽略现有变量?

这是功能:

由于多语言要求,单词需要来自数组。

function get_genre($id)
{
    if($id == "1"){
        $genre = $lang['277'];
    }
    if($id == "2"){
        $genre = $lang['278'];
    }
    if($id == "3"){
        $genre = $lang['279'];
    }
    if($id == "4"){
        $genre = $lang['280'];
    }
    if($id == "5"){
        $genre = $lang['281'];
    }
    if($id == "6"){
        $genre = $lang['282'];
    }
    if($id == "7"){
        $genre = $lang['283'];
    }
    if($id == "8"){
        $genre = $lang['284'];
    }
    if($id == "9"){
        $genre = $lang['285'];
    }
    if($id == "10"){
        $genre = $lang['286'];
    }
    if($id == "11"){
        $genre = $lang['287'];
    }
    if($id == "12"){
        $genre = $lang['288'];
    }
    if($id == "13"){
        $genre = $lang['289'];
    }
    if($id == "14"){
        $genre = $lang['290'];
    } 
    if($id == "15"){
        $genre = $lang['374'];
    }
    return $genre;
}    

3 个答案:

答案 0 :(得分:0)

function get_genre($id)
{
    global $lang;
    ....
}

function get_genre($id, $lang) //Must pass $lang array to function here
{

}

答案 1 :(得分:0)

function get_genre($id)
{
 global $lang;

if($id == "1"){
    $genre = $lang['277'];
}
if($id == "2"){
    $genre = $lang['278'];
}
if($id == "3"){
    $genre = $lang['279'];
}
if($id == "4"){
    $genre = $lang['280'];
}
if($id == "5"){
    $genre = $lang['281'];
}
if($id == "6"){
    $genre = $lang['282'];
}
if($id == "7"){
    $genre = $lang['283'];
}
if($id == "8"){
    $genre = $lang['284'];
}
if($id == "9"){
    $genre = $lang['285'];
}
if($id == "10"){
    $genre = $lang['286'];
}
if($id == "11"){
    $genre = $lang['287'];
}
if($id == "12"){
    $genre = $lang['288'];
}
if($id == "13"){
    $genre = $lang['289'];
}
if($id == "14"){
    $genre = $lang['290'];
} 
if($id == "15"){
    $genre = $lang['374'];
}
return $genre;

}

答案 2 :(得分:-1)

虽然这不理想,你考虑过使用关联数组吗?

var $lookupArray = array();
$lookupArray["1"] = $lang['274'];
....

然后你可以这样称呼它:

function get_genre($id)
{            

   return(array_key_exists($id,$lookupArray)) ? $lookupArray[$id] : null;                      

}