Home > Article > Backend Development > What are the types of php constants?
What are php constants?
The so-called constant is a quantity that cannot be changed. Once a PHP constant is defined, it cannot be changed or undefined. This is the official explanation and the most authoritative explanation.
php constants are usually used to store data that does not change and is not expected to change. The data can only be data of four scalar data types: integer (integer), floating point (decimal), character String, Boolean type (true/false).
Constants are divided into system built-in constants and custom constants.
The most common system built-in constants are __FILE__, __LINE__, PHP_OS, PHP_VERSION, PHP_OS, TRUE, etc.
php Naming rules for custom constants
The naming rules for PHP constants are similar to the naming rules for PHP variables but not exactly the same.
● PHP constant names must be composed of letters, underscores, and numbers;
● They cannot start with numbers;
● Whether to be case-sensitive is specified when defining;
● It is recommended to know the meaning when naming (you will know what it means when you see it), use English words as constant names, and it is recommended that the letters are all capital letters (such as: PI);
Naming of php constants:
<?php header("content-type:text/html;charset=utf-8");//设置编码,解决中文乱码 /*define("PI-1",3.14); 常量名错误,只能由字母、下划线、数字组成 * define("2PI",3.14);常量名错误,不能以数字开头 */ define("PI_2",3.14);//正确 define("PI_3",3.142);//正确 echo PI_2;//输出常量PI_2 echo " ";//输出空格 echo PI_3;//输出常量PI_3 ?>
Running result:
3.14 3.142
How to define PHP constants?
php constants are defined using the define() function. The define() function has two required parameters and one optional parameter. The first parameter specifies the name of the constant, also called an identifier; the second parameter specifies the value of the constant, which is a scalar data type that does not want to be changed; the third parameter is an optional parameter, used to specify the name of the constant. Is it case sensitive? If TRUE, constant names are case-insensitive; if FALSE (the default), they are case-sensitive.
Use the define() function to define constants:
<?php header("content-type:text/html;charset=utf-8");//设置编码,解决中文乱码 define("PI2",3.14);//区分大小写 define("PI3",3.142,true);//不区分大小写 echo PI2;//输出常量PI2 echo " ";//输出空格 echo pi3;//输出常量PI3 ?>
Running results:
3.14 3.142
Recommended learning: PHP tutorial
The above is the detailed content of What are the types of php constants?. For more information, please follow other related articles on the PHP Chinese website!