同一文件中函数内返回NULL的全局PHP变量
因此,我将局部变量$polls设置为包含JSON数组,但是当我从函数中对变量进行var_转储时,同一文件中的函数将返回NULL作为$poll的值同一文件中函数内返回NULL的全局PHP变量,php,json,Php,Json,因此,我将局部变量$polls设置为包含JSON数组,但是当我从函数中对变量进行var_转储时,同一文件中的函数将返回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_
$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不应该很容易就在范围内吗?我已经检查过$polls没有在我使用的代码库中的任何其他地方定义。将其作为参数传入:
function getPoll($polls) {
var_dump($polls);
}
getPoll($polls);
您需要使用
global
声明从函数内部访问全局变量:
function getPoll() {
global $polls;
var_dump($polls); //this returns NULL
}
全局命名空间中的变量在函数内部不可用,除非您显式地使它们可用。有三种方法可以做到这一点: 将其作为参数传递(推荐) 使用
全局
关键字(强烈不推荐)
使用$GLOBALS
superglobal(强烈不推荐)
试试这个
$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);
我看到您没有通过参数变量范围传递任何内容,函数本身不知道$polls的值是什么(或者称为$polls的变量甚至存在)。请不要继续推荐
global
,因为它是解决所有范围问题的万能灵丹妙药我不推荐它,我在回答关于如何做他想做的事情的问题。有趣的是,global
一开始对我都不起作用,所以解决方案已经出来了。没有理由global
不应该这样做。问题中一定有你没有解释正确的地方。我觉得这里可能有更大的问题。即使我使用了两个强烈不推荐的global$polls
和$polls=$GLOBALS['polls']代码>,它仍然无法正确地变量转储[$polls]
。你知道为什么吗?你试过第一种选择吗?
function getPoll(){
global $polls
var_dump($polls);
}
function getPoll(){
$polls = $GLOBALS['polls'];
var_dump($polls);
}
$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);