【问题标题】:PHP global variable modifier does not workPHP 全局变量修饰符不起作用
【发布时间】:2011-03-30 03:07:20
【问题描述】:

我的 index.php 中包含一个文件 (color.php)。在包含的文件中,我定义了一些变量和函数。

(color.php)

<?php
  $colors = array(0xffffff, 0x000000, 0x000000, 0x808080);
  function getColors() {
     global $colors;
     return $colors;
  }
?>

下面是我的主文件(index.php)。

<?php
      require_once('color.php');
      class Test {
           function Test() {
               var_dump(getColors()); // returns NULL
           }
      }
?>

为什么调用 getColors() 函数,它返回 NULL 应该返回一个颜色数组?我错过了什么吗?或者 php.ini 中是否需要任何配置?任何帮助将非常感激。谢谢!

【问题讨论】:

    标签: php function variables null global


    【解决方案1】:

    这对我来说很好用:

    <?php
    $colors = array(0xffffff, 0x000000, 0x000000, 0x808080);
    function getColors() {
        global $colors;
        return $colors;
    }
    class Test {
        function Test() {
            var_dump(getColors());
        }
    }
    $st = new Test();
    $st->Test();
    ?>
    

    【讨论】:

      【解决方案2】:
      function getColors() {
         return array(0xffffff, 0x000000, 0x000000, 0x808080);
      }
      

      至于为什么返回NULL,一定有一个很好的解释。

      也许你在某个地方打电话给unset($colors)

      【讨论】:

        【解决方案3】:

        这对我有用。我不确定您是在创建对 Test 类的新引用还是在调用该方法,但这有效。

          $colors = array(0xffffff, 0x000000, 0x000000, 0x808080);
          function getColors() {
             global $colors;
             return $colors;
          }
              class Test {
                   function __construct() {
                      if (getColors() == NULL) {
                        echo "null";// returns NULL
                      } else {
                        print_r(getColors());
                      }
                   }
              }
        
          $test = new Test();
        

        【讨论】:

          【解决方案4】:

          实际上,我已经弄清楚是什么导致了这个错误。我将文件包含在主类的一个函数中,所以声明

          global $colors; 
          

          包含文件中的函数 getColors() 返回 NULL,因为 $colors 未在主类之外定义。我在这里发布的代码只是我遇到问题的实际代码的虚拟表示。当我发布它时,我没有预料到这一点。我的错。无论如何,现在已经解决了。谢谢你们的回答。直到下一次。 :)

          【讨论】:

            猜你喜欢
            • 2010-10-20
            • 1970-01-01
            • 1970-01-01
            • 2013-09-21
            • 1970-01-01
            • 2013-07-13
            • 2016-12-30
            • 2017-07-19
            相关资源
            最近更新 更多