Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
只需向php函数添加代码_Php - Fatal编程技术网

只需向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 => $

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

$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); 

我想,如果你不传递变量或使它们成为
全局的
,它们就不会被识别。不过我不确定。