簡體   English   中英

PHP變量范圍和全局變量

[英]PHP Variable scope and globals

我有兩個php文件。 第一個文件將包括第二個文件。 所有這一切。 但是,在第二個文件中,我有一個數組:

//set required items
$reqSettings = array(
    "apiUser" => true,
    "apiPass" => true,
    "apiKey" => true,
);

在第一個文件中調用的函數中,我想遍歷此數組,但是該函數無法識別它:

function apiSettingsOk($arr) {
    global $reqSettings;

    $length = count($reqSettings);

    echo $length; //returns 0 and not 3
}

如您所見,我嘗試使用“全局”,但這也不起作用。 您能幫我解決這個問題嗎?

為了完整性起見,這是兩個文件;)

文件1:

$apiArr = array();

if (isset($_POST['api-submit'])) {

    $gateWay =  $_POST['of-sms-gateway'];
    $apiArr['apiUser'] = $_POST['api-user'];
    $apiArr['apiPass'] = $_POST['api-passwd'];
    $apiArr['apiKey'] = $_POST['api-key'];

    //including the gateway file
    include_once('of_sms_gateway_' . $gateWay . '.php');

    if (apiSettingsOk() === true) {
        echo "CORRECT";
    }

}

?>

of_sms_gateway_test.php:

<?php

//set required items
$reqSettings = array(
    "apiUser" => true,
    "apiPass" => true,
    "apiKey" => true,
);

function apiSettingsOk($arr) {
    global $reqSettings;
    $returnVar = true;

    $length = count($reqSettings);

    echo $length;

    return $returnVar;

}
?>

請在“ file2.php”中包含“ file1.php”,然后它將起作用。

范例:

file1.php

<?php

$array = array(
    "name" => "test"
);

?>

file2.php

<?php

 include_once("file1.php");

 function test()
 {
     global $array;
     echo "<pre>";
     print_r($array);
 }

 test();
?>

在這里,您可以看到,它將在file2.php中打印$ array。 在file1.php中聲明。

希望它會有所幫助。

您已將參數$ arr放到了您不提供的函數中。 像這樣:

if (apiSettingsOk($reqSettings) === true) {
    echo "CORRECT";
}

和功能

function apiSettingsOk($arr) {
echo count($arr); //returns 0 and not 3
}

非常感謝您的幫助。

使用該功能,我還發現將$ reqSettings聲明為第一個文件中的全局變量,並在第二個文件中的函數中聲明為全局變量有助於這樣做。

file1.php

<?php
    global $reqSettings;
    $apiArr = array();

    if (isset($_POST['api-submit'])) {

        $gateWay =  $_POST['of-sms-gateway'];
        $apiArr['apiUser'] = $_POST['api-user'];
        $apiArr['apiPass'] = $_POST['api-passwd'];
        $apiArr['apiKey'] = $_POST['api-key'];

        include_once('of_sms_gateway_' . $gateWay . '.php');

        if (apiSettingsOk($apiArr) === true) {

            echo "OK";

        } else {
            echo "ERROR";
        }

    }

?>

file2.php

<?php

    $reqSettings = array(
        "apiUser" => true,
        "apiPass" => true,
        "apiKey" => true,
    );

    function apiSettingsOk($arr) {
        global $reqSettings;
        $returnVar = true;

        $length = count($reqSettings);
        echo $lenght; //now shows 3

        return $returnVal;
    }

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM