在 PHP 中从外部文件加载变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2608693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:06:18  来源:igfitidea点击:

Load variables from external file in PHP

phpvariablesimportexternalconfig

提问by Adrian M.

How can I import a variable from an external file? What I want to do is to have a configuration file in which I can write all my website settings and then to import these settings to every file, so I can set the website skin and things like that.

如何从外部文件导入变量?我想要做的是有一个配置文件,我可以在其中写入我所有的网站设置,然后将这些设置导入每个文件,这样我就可以设置网站皮肤和类似的东西。

How can I do this?

我怎样才能做到这一点?

回答by remi bourgarel

回答by mandril

You can have a file with configuration and then include it on every script, like jeroen told you:

您可以拥有一个带有配置的文件,然后将其包含在每个脚本中,就像 jeroen 告诉您的那样:

config.inc.php

配置文件

$config['dbname'] = 'myDB';
$config['dbuser'] = 'user';

...

...

then in your scripts

然后在你的脚本中

include_once('config.inc.php');

You could also use inheritance where you have a model for example that uses the config and then you can extend that model class.

您还可以在您有一个模型的地方使用继承,例如使用配置,然后您可以扩展该模型类。

回答by PHPWDev

You can use auto_prepend_fileto prepend your settings in every PHP scripts that is executing. It's inside the php.ini, or you can use .htaccess(php_value auto_prepend_file "path/mysettings.php"), or using ini_set(). The file must be a valid or existing.

您可以使用auto_prepend_file在每个正在执行的 PHP 脚本中预先设置您的设置。它在 内php.ini,或者您可以使用.htaccess( php_value auto_prepend_file "path/mysettings.php") 或使用ini_set(). 该文件必须是有效的或存在的。

回答by jeroen

It depends on how you want to store your configuration. You can just include a php file that has stuff like:

这取决于您希望如何存储配置。您可以只包含一个包含以下内容的 php 文件:

$config['stuff'] = "value";

but you can also use a config (ini) file or a xml file. PHP has standard functions available to read config files or xml files, so that′s easy as well.

但您也可以使用配置 (ini) 文件或 xml 文件。PHP 具有可用于读取配置文件或 xml 文件的标准函数,因此也很容易。