只需向php函数添加代码
我想用以下代码创建一个php函数,但当我将其添加到函数时,它将停止工作:只需向php函数添加代码,php,Php,我想用以下代码创建一个php函数,但当我将其添加到函数时,它将停止工作: 代码工作: $arr = array( "index.php" => $home, "about.php" => $about, "details.php" => $details ); $url = basename($_SERVER['PHP_SELF']); foreach($arr as $key => $
代码工作:
$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
$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);
我想,如果你不传递变量或使它们成为
全局的
,它们就不会被识别。不过我不确定。