我想用以下代码创建一个php函数但是当我将它添加到一个函数时它会停止工作:
代码工作:
$arr = array(
"index.php" => $home,
"about.php" => $about,
"details.php" => $details
);
$url = basename($_SERVER['PHP_SELF']);
foreach($arr as $key => $value){
if($url == $key) {
echo $value;
}
}
代码不起作用:
function metaData() {
$arr = array(
"index.php" => $home,
"about.php" => $about,
"details.php" => $details
);
$url = basename($_SERVER['PHP_SELF']);
foreach($arr as $key => $value){
if($url == $key) {
echo $value;
}
}
}
metaData(); // NULL
答案 0 :(得分:2)
$home
,$about
和$details
都超出了您的职能范围。您需要将它们作为参数传递给该函数,以使它们可用于函数本身。
function metaData($home, $about, $details) {
$arr = array(
"index.php" => $home,
"about.php" => $about,
"details.php" => $details
);
$url = basename($_SERVER['PHP_SELF']);
foreach($arr as $key => $value){
if($url == $key) {
echo $value;
}
}
}
metaData($home, $about, $details);