Search code examples
phpreferencescopephp-include

Global variable assigned by reference inside a file included in a function


Below is a simplified example of how a certain 3rd party module adds a 3rd party application into a page. The application is normally meant to be standalone and accessed directly, but the module uses a function to include the application at a specific URL.

module.php:

if ($path == 'some/specific/url') {
  load_app();
}

function load_app() {
  include('./app.php');
}

app.php:

// For this example, assume $_SESSION['a'] already exists as an array of strings.

global $b;

$b = &$_SESSION['a'];

do_something();

function do_something() {
  global $b;

  // Do something with $b.

  // Problem: $b is always NULL when it should be an array.
}

The problem is that the line $b = &$_SESSION['a']; in app.php doesn't seem to work properly so $GLOBALS['b'] remains NULL which means $b is also NULL inside do_something().

This appears to be because app.php is included from within a function in module.php, so I assume it's something to do with the scope of app.php and the assignment by reference.

Unfortunately, I can't modify app.php at all and I can't move the include() outside of the load_app() function in module.php, so is there any other way that module.php can be altered to make app.php work as it is supposed to?


Solution

  • After much trial and error with inserting global $b; in various places in an effort to propagate the global variable, what finally worked for me was the following:

    module.php:

    function load_app() {
      $GLOBALS['b'] = &$_SESSION['a'];
      include('./app.php');
    }
    

    It seems that assigning the reference directly to $GLOBALS['b'] in module.php allows app.php to work properly without any modifications. Assigning the reference to global $b does not.