2011-03-30 94 views
0

我有一个文件(color.php)包含在我的index.php中。在包含的文件中,我定义了一些变量和函数。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中的任何配置?任何帮助将非常感激。谢谢!

回答

0
function getColors() { 
    return array(0xffffff, 0x000000, 0x000000, 0x808080); 
} 

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

也许你还能unset($colors)地方。

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(); 
?> 
0

这为我工作。我不确定你是否创建了一个新的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(); 
0

实际上,我已经找出了导致这个bug的原因。我包括内部的主类的功能之一的文件,这样的声明

global $colors; 
功能getColors的

()中包含的文件,因为$颜色不是主要的类外定义返回NULL。我在这里发布的代码只是我遇到的实际代码的虚拟表示。当我发布它时,我没有预料到这一点。我的错。无论如何,这是现在修复。谢谢你们的答案。直到下一次。 :)