Constants for beginners to PHP
One:What is a constant
After a constant value is defined, it cannot be changed anywhere else in the script
A constant is an identifier of a simple value , a constant consists of English letters, underscores, and numbers, but numbers cannot appear as the first letter. (Constant names do not need to be added with the $ modifier)
Note: Constants can be used throughout the script
2:Set PHP constants
Use define() function
Syntax format:
bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )
The define function has 3 parameters
1.name: required parameter, constant name, i.e. identifier
2.value: required parameter, constant value
3 .case_insensitive optional parameter, if set to TRUE, this constant is case-insensitive. The default is case-sensitive
<?php header("Content-type: text/html; charset=utf-8"); // 区分大小写的常量名 define("GREETING", "欢迎访问 taobao.com"); echo GREETING; // 输出 "欢迎访问 taobao.com" echo '<br>'; echo greeting; // 输出 "greeting" ?>
Note: This is case-sensitive, so an error will be reported
Let’s write a case-insensitive one
<?php header("Content-type: text/html; charset=utf-8"); // 不区分大小写的常量名 define("GREETING", "欢迎访问 taobao.com", true); echo greeting; // 输出 "欢迎访问taobao.com" ?>
Note: This will output "Welcome to taobao.com" without reporting an error
Constants can be used outside without quotation marks only Scalars can be used
<?php header("Content-type: text/html; charset=utf-8"); // 不区分大小写的常量名 define("GREETING",array(1,2,1,1)); echo greeting; // 输出 "欢迎访问淘宝" ?>
In addition, the system has also prepared some built-in constants for us as shown in the figure below