📅  最后修改于: 2020-09-26 03:45:04             🧑  作者: Mango
PHP常量是名称或标识符,在脚本执行期间不能更改,魔术常量除外,魔术常量不是真正的常量。PHP常量可以通过两种方式定义:
常量与变量相似,只不过一旦定义,就永远不能取消定义或更改它们。它们在整个程序中保持不变。PHP常数遵循相同的PHP变量规则。例如,只能以字母或下划线开头。
按照惯例,PHP常数应以大写字母定义。
注意:与变量不同,常量在整个脚本中都是自动全局的。
使用define()函数创建一个常量。它在运行时定义常量。让我们看看PHP中define()函数的语法。
define(name, value, case-insensitive)
让我们看一下使用define()定义PHP常量的示例。
文件:constant1.php
输出:
Hello JavaTpoint PHP
创建一个不区分大小写的名称常量:
文件:constant2.php
";
echo message;
?>
输出:
Hello JavaTpoint PHP Hello JavaTpoint PHP
文件:constant3.php
输出:
Hello JavaTpoint PHP Notice: Use of undefined constant message - assumed 'message' in C:\wamp\www\vconstant3.php on line 4 message
PHP引入了关键字const来创建常量。const关键字在编译时定义常量。它是一种语言构造,而不是一种函数。使用const关键字定义的常量区分大小写。
文件:constant4.php
输出:
Hello const by JavaTpoint PHP
还有一种使用constant()函数而不是echo语句来打印常量值的方法。
句法
以下常量函数的语法:
constant (name)
文件:constant5.php
";
echo constant("MSG");
//both are similar
?>
输出:
JavaTpoint JavaTpoint
Constant | Variables |
---|---|
Once the constant is defined, it can never be redefined. | A variable can be undefined as well as redefined easily. |
A constant can only be defined using define() function. It cannot be defined by any simple assignment. | A variable can be defined by simple assignment (=) operator. |
There is no need to use the dollar ($) sign before constant during the assignment. | To declare a variable, always use the dollar ($) sign before the variable. |
Constants do not follow any variable scoping rules, and they can be defined and accessed anywhere. | Variables can be declared anywhere in the program, but they follow variable scoping rules. |
Constants are the variables whose values can’t be changed throughout the program. | The value of the variable can be changed. |
By default, constants are global. | Variables can be local, global, or static. |