PHP global variable modifier does not work
I have a file(color.php) included in my index.php. In the included file, I have defined some variables and开发者_如何学C functions.
(color.php)
<?php
$colors = array(0xffffff, 0x000000, 0x000000, 0x808080);
function getColors() {
global $colors;
return $colors;
}
?>
Below is my main file(index.php).
<?php
require_once('color.php');
class Test {
function Test() {
var_dump(getColors()); // returns NULL
}
}
?>
Why is it that calling the getColors() function, it returns NULL which is supposedly, will return an array of colors? Am I missing something? Or is there any config needed in php.ini? Any help would be much appreciated. Thanks!
This works fine for me:
<?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();
?>
function getColors() {
return array(0xffffff, 0x000000, 0x000000, 0x808080);
}
As to why it's returning NULL
, there must be a good explanation.
Perhaps you call unset($colors)
somewhere.
this worked for me. I'm not sure if you were creating a new reference to the Test class or calling the method, but this worked.
$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();
Actually, I already figured out what caused this bug. I included the file inside one of the functions of the main class, so the statement
global $colors;
of function getColors() in the included file returns NULL because $colors was not defined outside the main class. The code I posted here was just a dummy representation of the actual code I'm having trouble with. I did not anticipate this one when I posted it. My bad. Anyway, this is fix now. Thank you guys for your answers. Till next time. :)
精彩评论