Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

Laravel 4: Why does my class autoload but global variables are not available

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"?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...