Concept
Constant can be understood as: a long-lasting value. After the constant value is defined, it cannot be changed anywhere else in the script.
1. Composition of constants
The writing form of constants is define(constant name, constant)
Note:
Constant names can be lowercase, but usually uppercase
Constant names can be without quotation marks, but usually with quotation marks.
When calling a constant in a string, it must be outside the quotation marks
It is recommended that only letters and underscores be used for constant names
Let’s define and call a constant:
Example:
<?php //定义一个常量 define('Name','PHP.com'); //正确的调用方式 echo '我们是'.Name; echo '<br/>'; //错误的调用方式 echo '我们是Name'; ?>
Next, let’s verify several statements about constants
Example :
<?php //其实可以小写,但是不好区分出来,所以习惯上大家都大写 define('age',27); echo age; //常量可以在外面不加引号 define(A,'安徽省'); echo A; //只能用于标量,用于其他会报错,例如数组 define('HF',array(1,2,3)); echo HF; ?>
Note 1: The constant definition is not quoted and can be output normally, but PHP will remind us that the definition is not standardized. Here Ntice
can Eliminate it by modifying the PHP configuration file. If you are interested, you can search and try to solve it yourself.
Note 2: The seven data types mentioned earlier can also be divided into three major categories
Scalar data types: Boolean, Integer, floating point, string
Composite data type: array, object
Special data type: NUll, resource type, callback Function
Note 3: After a constant is defined, it is a global variable by default and can be used anywhere in the entire running script.
2. Some built-in constants
The system also prepares some built-in constants for us. These constants are specified. Let’s get familiar with a few first. There are more system constants that we have studied in the previous volume. After getting started, we will slowly add and learn them.
##Constant name | Description |
__LINE__ | The current line |
The path of the current file on the server | |
Current function name | |
__CLASS__ | Current class name |
##__METHOD__ | The operating system PHP runs on |
Current PHP Version | |
##Trait name, added in php5.4 | |
The directory where the file is located | |
The name of the current namespace (case sensitive) |