定义与 PHP 中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1225082/
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
DEFINE vs Variable in PHP
提问by JasonDavis
Can someone explain the difference between using
有人可以解释使用之间的区别吗
define('SOMETHING', true);
and
和
$SOMETHING = true;
And maybe the benefits between one or the other?
也许两者之间的好处?
I use variables everywhere and even in a config type file that is included to everypage I still use variables as I don't see why to use the define method.
我在任何地方都使用变量,甚至在每个页面都包含的配置类型文件中,我仍然使用变量,因为我不明白为什么要使用定义方法。
回答by Tyler Carter
DEFINE makes a constant, and constants are global and can be used anywhere. They also cannot be redefined, which variables can be.
DEFINE 生成一个常量,常量是全局的,可以在任何地方使用。它们也不能重新定义,哪些变量可以。
I normally use DEFINE for Configs because no one can mess with it after the fact, and I can check it anywhere without global-ling, making for easier checks.
我通常将 DEFINE 用于配置,因为事后没有人可以弄乱它,而且我可以在没有 global-ling 的任何地方检查它,使检查更容易。
回答by karim79
Once defined, a 'constant' cannot be changed at runtime, whereas an ordinary variable assignment can.
一旦定义,“常量”就不能在运行时改变,而普通的变量赋值可以。
Constants are better for things like configuration directives which should not be changed during execution. Furthermore, code is easier to read (and maintain & handover) if values which are meant to be constant are explicitlymade so.
常量更适合在执行期间不应更改的配置指令之类的内容。此外,如果显式地设置了旨在保持不变的值,则代码更易于阅读(以及维护和切换)。
回答by Randy Greencorn
There is also a difference in scope.
范围也有区别。
In the example given by the orignal poster, $SOMETHINGwill not be accessible within a function whereas define('SOMETHING', true)will be.
在原始海报给出的示例中,$SOMETHING将无法在函数中访问,而define('SOMETHING', true)可以。
回答by user128026
define()makes a read-only variable, compared to a standard variable that supports read and write operations.
与支持读写操作的标准变量相比,define()是一个只读变量。
回答by Geoffrey Eng Atkinson
A constant is very useful when you want access data from inside a function, check this
当您想从函数内部访问数据时,常量非常有用,请检查此
<?php
function data(){
define("app","hey you can see me from outside the function",false);
$tech = "xampp";
}
data();
echo $tech;
echo app;
?>
If you use a variable you are never going to get the inside value here is what i get
如果你使用一个变量,你永远不会得到内部值,这就是我得到的
Notice: Undefined variable: tech in D:\xampp\htdocs\data\index.php on line 8 hey you can see me from outside the function
注意:未定义变量:tech in D:\xampp\htdocs\data\index.php 第 8 行嘿你可以从函数外看到我

