php 更改先前定义的常量的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8481869/
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
Change the value of a previously-defined constant
提问by Carl Thomas
I have defined a constant in PHP e.g.
我在 PHP 中定义了一个常量,例如
define('CONSTANT_NAME', 'constant_value');
I want to be able to change the value of this constant later on in the code.
我希望能够稍后在代码中更改此常量的值。
Can this be done? If so, how?
这能做到吗?如果是这样,如何?
回答by Oliver Charlesworth
From http://php.net/manual/en/function.define.php(emphasis is mine):
来自http://php.net/manual/en/function.define.php(重点是我的):
define
— Defines a named constant
define
— 定义一个命名常量
From http://www.php.net/manual/en/language.constants.php:
从http://www.php.net/manual/en/language.constants.php:
As the name suggests, that value cannot change during the execution of the script
顾名思义,该值在脚本执行期间不能更改
回答by kenorb
It is possible to redeclare define, when it was previously defined as case_insensitive constant (3rd parameter).
当定义之前定义为 case_insensitive 常量(第三个参数)时,可以重新声明定义。
See:
看:
$ php -r "define('TEST','foo',true); var_dump(TEST); define('TEST','bar'); var_dump(TEST);"
string(3) "foo"
string(3) "bar"
Tested with PHP CLI 5.2.6 and 5.5.3.
使用 PHP CLI 5.2.6 和 5.5.3 进行测试。
回答by Kristian Hildebrandt
You didnt create a variable, you created a constant. The point of a constant is, that they cannot be changed.
您没有创建变量,而是创建了一个常量。常数的要点是,它们不能改变。
You should use a true variable instead.
您应该改用真正的变量。
回答by Ronak Dhoot
Just for work around, passing 3rd param as true will help you
只是为了解决,将第三个参数传递为 true 会帮助你
define('CONSTANT_NAME', 'constant_value', true);
print CONSTANT_NAME.PHP_EOL;
define('CONSTANT_NAME', 'constant_value2');
print CONSTANT_NAME.PHP_EOL;
回答by Blackbam
Well there is a way to change previously defined constants. You have to enable the PHP runkit extension for this purpose: http://php.net/manual/en/function.runkit-constant-redefine.php
好吧,有一种方法可以更改先前定义的常量。为此,您必须启用 PHP runkit 扩展:http://php.net/manual/en/function.runkit-constant-redefine.php
The runkit extension provides means to modify constants, user-defined functions, and user-defined classes. It also provides for custom superglobal variables and embeddable sub-interpreters via sandboxing.
runkit 扩展提供了修改常量、用户定义函数和用户定义类的方法。它还通过沙箱提供自定义的超全局变量和可嵌入的子解释器。
It gives you the power to modify whatever aspect you want to modify within PHP. This is advanced stuff though.
它使您能够在 PHP 中修改您想要修改的任何方面。不过这是高级的东西。
Please note that there is usually a reason for constants to be defined as constants therefore changing this for other purposes than testing is probably not a good idea in almost any case.
请注意,将常量定义为常量通常是有原因的,因此在几乎任何情况下,出于测试以外的其他目的更改它可能都不是一个好主意。