全局PHP变量在同一文件内的函数内返回NULL

时间:2014-03-31 22:27:03

标签: php json

所以我设置了一个局部变量$ polls来包含一个JSON数组,但是当我在函数中执行变量的var_dump时,同一文件中的函数将返回NULL作为$ poll的值

$polls = json_decode(file_get_contents($lib_path . '/polls.json'), true);
var_dump($polls); //this returns the information within $polls correctly

function getPoll() {
    var_dump($polls); //this returns NULL
}

我已经尝试(徒劳)使用全球'但是不应该将$民意调查轻松放在范围内?我已经检查过$ polls尚未在我正在使用的代码库中的任何其他地方定义。

4 个答案:

答案 0 :(得分:4)

全局命名空间中的变量在函数内部不可用,除非您明确地这样做。有三种方法可以做到这一点:

将它们作为参数传递(推荐)

function getPoll($polls){
    var_dump($polls);
}

使用global关键字(强烈不推荐)

function getPoll(){
    global $polls
    var_dump($polls);
}

使用$GLOBALS超全球(强烈不推荐)

function getPoll(){
    $polls = $GLOBALS['polls'];
    var_dump($polls);
}

答案 1 :(得分:1)

试试这个

$polls = json_decode(file_get_contents($lib_path . '/polls.json'), true);
var_dump($polls); //this returns the information within $polls correctly

function getPoll($p) {
var_dump($p); //this returns NULL
}
//call class
getPoll($poll);

我看到你没有通过参数传递任何东西

答案 2 :(得分:0)

将其作为参数传递:

 function getPoll($polls) {
   var_dump($polls); 
 }

 getPoll($polls);

答案 3 :(得分:0)

您需要使用global声明来从函数内部访问全局变量:

function getPoll() {
    global $polls;
    var_dump($polls); //this returns NULL
}

DEMO

相关问题