PHP中的变量常量 [英] Variable constants in PHP
问题描述
是否可以在PHP中更改常量的值?我们希望为项目的配置文件提供合理的默认值。
Is it possible to change the value of a constant in PHP? We want sensible defaults for the configuration files for our project.
当前,我们正在执行以下操作:
Currently we are doing:
config.php :
config.php:
define('WEB_ROOT', '/home/user/public_html');
config.default.php:
config.default.php:
defined('WEB_ROOT') || define('WEB_ROOT', '/home/user/public_html');
问题是,在某些情况下,您可能想从'config内部访问某些配置默认值。 php。例如:
The problem is that in certain cases, you may want to access certain configuration defaults from inside 'config.php'. For example:
config.php
config.php
define('USER_FILE_ROOT', WEB_ROOT.'/files');
带有配置常量的方案已经使用了5年,并且不能重写框架。
The scheme with constants for configuration has been used for 5 years, and rewriting the framework is not an option.
推荐答案
结果可以!
首先声明默认值。像这样:
First declare the defaults like this:
define('WEB_ROOT', '/var/www', TRUE);
然后包含配置文件:
define('WEB_ROOT', '/home/user/public_html');
此代码效果很好:
define('FOO', 'BAR', TRUE);
echo FOO; // outputs BAR
define('FOO', 'FOOBAR');
echo FOO; // outputs FOOBAR
这是一个令人难以置信的事实,即PHP支持声明不区分大小写的常量。
This is a side effect of the incredible fact that PHP supports declaring case insensitive constants.
这篇关于PHP中的变量常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!