jcagumbay
jcagumbay

Reputation: 61

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 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!

Upvotes: 0

Views: 1198

Answers (4)

jcagumbay
jcagumbay

Reputation: 61

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. :)

Upvotes: 0

Chris McClellan
Chris McClellan

Reputation: 1105

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

Upvotes: 0

Jess
Jess

Reputation: 8700

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

Upvotes: 1

Matthew
Matthew

Reputation: 48284

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.

Upvotes: 0

Related Questions