PHP全局数组未显示


PHP global array not showing

考虑以下函数,该函数用字符串(问题)填充数组:

global $questions;
function printQuestions($lines){
    $count = 1;
    foreach ($lines as $line_num => $line) {
        if($line_num%3 == 1){
            echo 'Question '.$count.':'.'<br/>'.'<input type="text" value="' . $line . '" class="tcs"/>'.'<br/>';
            $count++;
            $questions[] = $line;
        }
    }
}

问题数组被定义为全局数组,但在函数之外无法访问。位于页面底部的以下代码块不返回任何内容:

<?php
    if(isset($_POST['Submit'])){
        foreach($questions as $qs)
            echo $qs;   
        }
?>

我知道我可以使用会话变量,但我对这个关于全局变量的特殊问题感兴趣。非常感谢您的帮助。

您应该在函数内移动global

function printQuestions($lines){
    global $questions;
    // ...

global关键字将全局变量带入局部作用域,因此您可以对其进行操作。如果您不在printQuestions()函数中使用global将全局$questions变量带入函数作用域,则$questions将是局部变量,并且与您要查找的全局变量不同。

您可以在PHP中使用全局变量$GLOBALS["foo"],因此在您的情况下,在函数内部用$GLOBALS["questions"]替换$questions,一切都应该正常。