Search code examples
phpglobal-variables

Problem with accessing a global variable in PHP


Following is code snippet :

function something() {
$include_file = 'test.php';
if ( file_exists($include_file) ) {
    require_once ($include_file);
//      global $flag;
//        echo 'in main global scope flag='.$flag;
    test();
   }
}

something();

exit;

 //in test.php

$flag = 4;
function test() {
   global $flag;

   echo '<br/>in test flag="'.$flag.'"';
   if ($flag) {
       echo 'flag works';
     //do something
   }
}

The above code snippet, echoes 'global scope' $flag value properly but doesnt recognises the $flag with value 4, assumes null value for $flag . Please point out what is wrong in accessing that $flag global variable.


Solution

  • $flag = 4; is not in the global scope.

    If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function.

    -- PHP Manual page for include, which also applies for include_once, require, and require_once

    I'm going to make a guess that the error you're getting is on the if ($flag) line, because at that point, $flag is uninitialized, because the global $flag variable has never been assigned a value.

    Incidentally, echo 'global scope flag='.$flag; isn't displaying the global flag either, as you need a global $flag; in that function to display the global copy, which also has the side effect of making $flag = 4; affect the global copy in the included file.