【问题标题】:global PHP variable returning NULL within function inside same file全局 PHP 变量在同一文件内的函数内返回 NULL
【发布时间】:2014-03-31 22:27:03
【问题描述】:

所以我设置了一个局部变量 $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 不应该轻易地在范围内吗?我已经检查了 $polls 没有在我正在使用的代码库中的其他任何地方定义。

【问题讨论】:

标签: php json


【解决方案1】:

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

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

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

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

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

使用$GLOBALS superglobal(强烈不推荐)

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

【讨论】:

  • 我觉得这里可能有更大的问题。即使我使用了两个强烈不推荐的global $polls;$polls = $GLOBALS['polls'];,它仍然不会正确var_dump[$polls]。任何洞察为什么会这样?
  • 你试过第一个选项了吗?
【解决方案2】:

试试这个

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

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

【讨论】:

    【解决方案3】:

    作为参数传入:

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

    【讨论】:

      【解决方案4】:

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

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

      DEMO

      【讨论】:

      • 请不要一直推荐global作为解决所有范围问题的万能药
      • 我不是推荐它,我是在回答关于如何做他想做的事情的问题。
      • 很有趣,global 甚至对我都不起作用,所以这个解决方案已经出来了。
      • global 没有理由不这样工作。问题中一定有你没有正确解释的地方。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      相关资源
      最近更新 更多