取消设置或更改已定义的常量 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16497125/
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
unset or change a defined constant PHP
提问by Alex Ruhl
assumed i define a variable like this:
假设我定义了一个这样的变量:
<?php
define("page", "actual-page");
?>
now i have to change this content from actual-page
to second-page
how can i realize that?
现在我有这个内容从改变actual-page
到second-page
我如何能实现呢?
i try the following methods:
我尝试以下方法:
<?php
// method 1
page = "second-page";
// method 2
define("page", "second-page");
// method 3
unset(page);
define("page", "second-page");
?>
now my ideas goes out... what can i do else?
现在我的想法消失了……我还能做什么?
回答by Juampi
When you use PHP's define() function, you're not defining a variable, you're defining a constant. Constants can't have their value modified once the script starts executing.
当您使用 PHP 的 define() 函数时,您不是在定义变量,而是在定义常量。一旦脚本开始执行,常量就不能修改它们的值。
回答by Cobra_Fast
You can, with the runkit PECL extension:
您可以使用 runkit PECL 扩展:
runkit_constant_remove('page');
http://php.net/runkit_constant_remove
http://github.com/zenovich/runkit
http://php.net/runkit_constant_remove
http://github.com/zenovich/runkit
sudo pecl install https://github.com/downloads/zenovich/runkit/runkit-1.0.3.tgz
Update: This module seems to cause trouble with various other things, like the session system for example.
更新:此模块似乎会导致各种其他问题,例如会话系统。
回答by Mihai Pop
Maybe a very late answer, but the question was "now my ideas goes out... what can i do else?"
也许一个很晚的答案,但问题是“现在我的想法消失了......我还能做什么?”
Here is what you can do "else" - use $GLOBALS:
这是你可以做的“其他” - 使用 $GLOBALS:
<?php
// method 1
$GLOBALS['page'] = 'first-page';
// method 2
$GLOBALS['page'] = "second-page";
// method 3
$GLOBALS['page'] = 'third-page';
?>
I hope it helps. I use it when I do imports and I want specific events not to be fired if the import flag is on for example :)
我希望它有帮助。我在执行导入时使用它,并且我希望在导入标志打开的情况下不触发特定事件,例如 :)
回答by Shudmeyer
definehas a third argument (boolean) which override the first defined constant to the second defined constant. Setting the first defined constant to true.
define有第三个参数 (boolean),它将第一个定义的常量覆盖为第二个定义的常量。将第一个定义的常量设置为true。
<?php
define("page", "actual-page", true);
// Returns page = actual-page
define("page", "second-page");
// Returns page = second-page
?>