Laravel 4: Why does my class autoload but global variables are not available
laravel, laravel-4
Solution
This is an issue with Composer rather than Laravel. Composer makes every effort not to pollute the global scope during autoloading (discussed briefly in #1297). If you want to force global variables then you should declare them as global in your config file, as well as in any function using them.
The PHP Manual says:
Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.
The below code works for me (with Laravel 4b4 on PHP 5.4.13). Removing either global line breaks the code (in different ways).
config.php
global $connection_settings;
$connection_settings = array(/* ... */);
DB.php
require 'config.php';
class DB {
static function connect()
{
global $connection_settings;
// Do something with $connection_settings
}
}
Problem
I've autoloaded a class, which is properly namespaced and PSR-0. I put it in app/lib/CI, and the class and it's filename are the same "DB". The class file itself includes a config file before the actual class: ``` require( 'config.php' ); class DB { // ... } ``` The class is clearly autoloading, because when I call the static method connect it does display an error message from inside ::connect(). The problem is, global variables that are inside the included config.php are not available inside the class::method. So, to be clear, the array $connection_settings is inside config.php, but even when using: ``` global $connection_settings; ``` $connection_settings is not set inside the connect method. Something interesting is that even though the class is autoloaded, if I include the class from the top of my routes.php file, everything works normally. So what am I not doing right to get autoloading to work the way I consider "normal"?