简体   繁体   中英

include php file only once in project

I have a file (config.php) which has my app configuration data:

<?php

return [
    // here is my associative configuration array
    // having also Closures in it
];

What I do is sending this file to my Config class which will manipulate my data and it'll be my interface for configuration info.

Config::init(require('config.php'));

It that way, I don't want to can acces configuration info in any other way than using public Config class methods.

So, I need to can include config.php only once in my project (when is sent to Config class).

A solution would be with defining a constant in the top of file:

<?php

define('config', true);

return [
    // here is my associative configuration array
    // having also Closures in it
];

In that way, including config.php twice will generate error because 'config' constant get defined twice, which is illegal in php.

BUT, 'config' constant can easily be removed before second include. With:

runkit_constant_remove('config');

That's why I need to ask you for a more safe/trusty solution which can guarantee that configuration info can be taken only from Config class.

I suggest doing it with an ini file. Simple example below:

config.ini

[app]
user = myuser
pass = 123123
stage = 1

your config init:

Config::init(parse_ini_file('app.ini'));

parse_ini_file docu click here

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