0

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!

4 Answers 4

1

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();
?>
Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.