简体   繁体   中英

PHP encapsulate global variables

I have settings.php file that I want to keep some constants in, like my db connect info.

What I want to accomplish, but for the life of me, I can't figure how to do it is ... I don't want every constant in my settings.php globally available. I'm using an MVC setup and for example I don't my my db connection info available in my controller.

My question is, how do I setup a settings file like this:

class Settings {

  const HOST = 'localhost';

  ....

  const DEBUG = true;
}

then load it into my application so that my db connection constants are encapsulated into just my Model class and so on.

I'm sure I am not explaining this the best I could be, but basically I want to A: have one central location for all of settings and B: make it so that I can control access to those settings throughout my application so that they are not all globally available.

The problem I have run into is that if I include the settings.php file in my parent class then all of the classes that inherent from it also have access to settings.php.

Wrap them in a function and call it, eg

function init() {
    $model = new Model;
    $model->setConfigurationValue('name', 'value);
    // etc ...
}
init();

This way nothing is global.

Personally, I use the symfony components YAML library to store my configuration in YAML files which get automatically loaded into a singleton Configuration object, which allows access from everywhere but prevents the state from changing. Easy to change config without messing with code, and I use multiple YAML files so that my DEV environment adds extra config etc.

I would define your class in a file called "local_settings.php". Just "include" the file and instansiate your class this at the top of your php programs.

FOr everybody that whinges about globals these really are the sort of values that are global! You are unlikely to have another class that wants to work on adifferent version of your model connecting to a different DB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM