Home >Backend Development >PHP Tutorial >PHP constant declaration and use - Detailed explanation of the definition method of php constants
How to declare PHP constants
Constants can be understood as unchanging quantities. Once a constant is defined, it cannot be changed anywhere else in the script. A constant consists of English letters, underscores, and mathematics. But numbers cannot appear as initial letters.
Use define()function in PHP to define constants. The syntax format is as follows:
define(string constant_name,mixed value,case_sensitive=true)
Parameter description:
constant_name | Required parameter. Constant name, i.e. identifier. |
value | Required parameter. The value of the constant. |
case_sensitive | Optional parameters. Specify whether to be case sensitive. Set to true to indicate insensitivity. |
There are two ways to obtain constants: one is to obtain them directly using constants; the other is to use the constant() function, constant () function has the same output effect as using the constant name directly. But the function can dynamically output different constants, making it more flexible and convenient to use. The function syntax format is:
mixde constant(string const_name)
The parameter const_name is the name of the constant to be obtained, or it can be a variable that stores the constant name. If the acquisition is successful, the constant value is returned, otherwise Error message The constant is not defined.
To determine whether a constant has been defined, you can use the define() function. The function syntax format is:
bool defined(string constant_name)
The parameter constant_name is the name of the constant to be obtained. It returns true if successful, otherwise it returns false.
Usage examples of PHP constants:
In order to better understand how to define constants, here is an example of defining constants. The above three functions, define() function, constant() function and defined() function, are used in the example. Use the defined() function to define a constant, use the constant() function to dynamically obtain the value of the constant, and use the define() function to determine whether the constant is defined. The code is as follows:
<?php define("MESSAGE","能看到一次"); echo MESSAGE."<br >"; echo Message."<br >"; //输出Message,表示没有该常量 define("COUNT","能看到多次",true); echo COUNT."<br >"; echo CoUnT."<br >"; //输出COUNT,设定大小写不敏感 $name = "count"; //通过constant()函数获取常量 echo constant($name)."<br >"; //是否存在常量 "MESSAGE" echo (defined("MESSAGE"))."<br >"; //如果常量被定义,则返回true,使用echo输出显示1。 ?>
Output result:
能看到一次 Notice: Use of undefined constant Message - assumed 'Message' in 编辑器代码错误位置。 Message 能看到多次 能看到多次 能看到多次 1
The above is the detailed content of PHP constant declaration and use - Detailed explanation of the definition method of php constants. For more information, please follow other related articles on the PHP Chinese website!