如何更改PHP常量?

时间:2012-01-29 19:20:30

标签: php constants

我正在手工制作我自己的PHP自定义CMS,并且我已经定义了一些常量。有一种简单的方法来修改常量吗?我正在考虑使用类似fopen()之类的内容然后更改它,但我从未使用过文件系统函数。

8 个答案:

答案 0 :(得分:26)

  

常量是简单值的标识符(名称)。 作为名称   建议,在执行脚本期间,该值不能更改   (魔术常数除外,它们实际上不是常量)。一个   常量是默认情况下区分大小写。按照惯例,不变   标识符总是大写的。

     

常量的名称遵循与PHP中任何标签相同的规则。一个   有效的常量名称以字母或下划线开头,后跟   任意数量的字母,数字或下划线。作为一个常规   表达,它将如此表达:   [A-ZA-Z_ \ x7f- \ XFF] [A-ZA-Z0-9_ \ x7f- \ XFF] *

来自:http://php.net/manual/en/language.constants.php

答案 1 :(得分:15)

常量是常量,因此无法更改。 如果你想改变服务器常量,例如allow_url_fopen,那就是主机的责任,请问他们。 如果要在PHP中更改它们,请使用变量

<强>更新

如果真相是Corbin所说的并且您想在安装中修改它们,您可能希望执行以下操作:0。将常量值更改为sg。比如%%constant1。 1.将代码读入变量。 2.让用户设置变量。 3.对所有这些使用str_replace,如str_replace(“%% constant1”,$ _ POST [“value1”],$ configfile)。 4.将$ configfile作为文件的内容。

更新2

对于您自己的CMS,我建议如下:将所有常量存储在一个文件中,因此您只需要编辑一个文件。也许比以前的解决方案可以更容易编辑,但IDK是否值得花时间。

答案 2 :(得分:14)

没有。它们是常量,如“constant - 永久或不变的”(维基词典)。一旦定义它们,就无法改变它们。引用The Fine Manual,部分常量:

  在执行脚本期间,

[常量]值不能改变。

答案 3 :(得分:6)

没有。你无法修改常量

答案 4 :(得分:1)

in PHP, but only if you have the runkit extension installed.

However, I must question why you're even defining a constant if you need to change it.  It would no longer be a constant once changed and it's appropriate to use constants in your context if it needs to be changed.  You may want to consider making it a global variable if it needs to be accessible in other functions or parts of your code, or write proper code by:
Passing the data as parameters to a function, then returning the manipulated values (if coding in a procedural fashion).
Set the value in a class' property, then access the value using $this within your class (if coding in an OO fashion).

答案 5 :(得分:0)

据我所知,一旦设定,就不能改变常数。

答案 6 :(得分:0)

常量表示值是常量,因此您无法更改常量。如果要更改常量,则需要在常量状态下使用变量:

define('ROOT', '/some/path');
echo ROOT; // echo's /some/path
define('ROOT', '/some/other/path'); // gives an error
echo ROOT; // gives /some/path (if there were no error

$root = '/some/path';
echo $root; // echo's /some/path
$root = '/some/other/path';
echo $root; // echo's /some/other/path

答案 7 :(得分:0)

我认为他意味着安装程序脚本,他希望将输入变量存储到配置文件中,以便在安装完成后在CMS中使用。 在那种情况下,他不会在运行时更改常量。

他可能有这样的文件:

define(DB, '');
define(USER, '');
define(PASS, '');
define(HOST, '');

他想创建一个脚本,用数据填充这些常量,以便在CMS中使用。