只需将代码添加到php函数中

时间:2016-09-11 19:14:08

标签: php

我想用以下代码创建一个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

1 个答案:

答案 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);