Syntax
You can use the define() function to define constants. After PHP 5.3.0, you can use The const keyword defines constants outside the class definition. Once a constant is defined, it cannot be changed or undefined.
Constants can only contain scalar data (boolean, integer, float and string). can be defined resource Constant, but should be avoided as it will cause unpredictable results.
You can get the value of a constant simply by specifying its name. Unlike variables, should not be added in front of a constant $ symbol. If the constant name is dynamic, you can also use the function constant() to get the value of the constant. use get_defined_constants() can get a list of all defined constants.
Note: Constants and (global) variables are in different namespaces. This means for example
TRUE
and $TRUE are different.
If an undefined constant is used, PHP assumes that what is wanted is the name of the constant itself, as if calling it with a string (CONSTANT corresponds to "CONSTANT"). At this point a E_NOTICE level error. See the manual why $foo[bar] is wrong (unless it is previously defined with define() bar is defined as a constant). If you just want to check whether a certain constant is defined, use the defined() function.
Constants and variables have the following differences:
Example #1 Define constants
<span></span>
<?phpdefine("CONSTANT", "Hello world.");echo CONSTANT; // outputs "Hello world."echo Constant; // 输出 "Constant" 并发出一个提示级别错误信息?>
Example #2 Use keyword const to define constants
<span></span>
<?php// 以下代码在 PHP 5.3.0 后可以正常工作const CONSTANT = 'Hello World'; echo CONSTANT;?>
Note:
In contrast to using define() to define constants, using the const keyword to define constants must be in the topmost scope, because this method is defined at compile time. This means that it cannot be used inside functions, loops and if statements. const to define constants.
Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.
The above introduces the official document explanation of PHP constants, including relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.