开发者

Cross-file PHP variables?

I have a bunch of database addresses and other random long strings that I must input into functions again and again all over my site. Is there a way to make a ton of permanent, global variables in PHP that will be valid on a开发者_如何转开发ny file on the current PHP installation?

Or should I just make a vars.php with all of the variables defined, and always include that file?


Create your file with the settings you need. Something like this:

<?php
    // My file name might be config.php
    $config = array(
        'db.connection' => 'localhost:3306'
        // etc...
    );
?>

Then include it into each page/file that needs it.

<?php
    require("path-to/config.php");

    // Other stuff this file does/needs
?>


The answer is, well, both! Use prepend.

http://www.electrictoolbox.com/php-automatically-append-prepend/


Well you could use $GLOBALS variable, which also contains other superglobals like $_GET, $_POST etc. Of course that means you should still always include file where you define your own custom variable.

The good thing when using $GLOBALS is you can use it in all scopes, and at least imho you can use it as a sort of a namespacing technique.

For example if you use

$settings = array('host' => 'localhost');
    function connect() {
        global $settings;
    }

there's a possibility that you unintentionally override $setting variable at some point. When using $GLOBALS, I think this kind of scenario is not so likely to happen.

$GLOBALS['_SETTINGS'] = array(... => ...);
    function connect() {
       $settings = $GLOBALS['_SETTINGS'];
    }

Another solution would be using your own custom class, where you store your settings in a static array. Again, this requiers including file, where you define the class, but your data will be avialable within all scopes and cannot be acidently overriden.

Example:

class MySettings {

    private static $settings = array(
        'host' => 'localhost',
        'user' => 'root'
    );

    public static get($key) {
        return self::$settings[$key];
    }

}

function connect() {
    $host = MySettings::get('host');
    ...
}

Not saying it's the best way for doing this, but surely one way for accomplishing your goal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜