简体   繁体   English

在项目中仅包含一次php文件

[英]include php file only once in project

I have a file (config.php) which has my app configuration data: 我有一个文件(config.php),其中包含我的应用程序配置数据:

<?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类,该类将处理我的数据,它将作为我的配置信息接口。

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. 这样,除了使用公共Config类方法之外,我不想以任何其他方式访问配置信息。

So, I need to can include config.php only once in my project (when is sent to Config class). 因此,我只需要在项目中包含config.php一次(发送到Config类时)。

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. 这样,两次包含config.php都会产生错误,因为'config'常量被两次定义,这在php中是非法的。

BUT, 'config' constant can easily be removed before second include. 但是,“ config”常量可以很容易地在第二个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. 这就是为什么我需要问您一个更安全/可信赖的解决方案,该解决方案可以保证只能从Config类获取配置信息。

I suggest doing it with an ini file. 我建议用一个ini文件。 Simple example below: 下面的简单示例:

config.ini 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 parse_ini_file文档单击此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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