Home > Article > Backend Development > Definition and use of constants in php
Constant needs to be assigned a value when it is defined, and the value cannot be modified during operation. Valid constant names start with a character or an underscore, and there is no $ sign in front of the constant name. Unlike variables, constants are automatically global throughout the entire script.
Declare constants
If you need to set a constant, you can use define(constantName, constantValue, isCase)Function, which uses three parameters:
The first parameter defines the name of the constant
The second parameter defines the value of the constant
The third parameter is Optionally, specifies whether constant names are case-sensitive. The default is false.
For example
define("PI",3.14);定义一个常量 $area = PI*R*R; 计算圆的面积 define("URL","http://www.php.cn"); echo "我的网址是:".URL;
A constant is a simple identifier. This value cannot be changed during the execution of the script (except for the so-called magic constants, which are not actually constants). Constants are case-sensitive by default. Normally constant identifiers are always uppercase.
You can use the define() function to define constants. After php5.3.0, you can use the const keyword to define constants outside the class definition. In previous versions, the const keyword can only be used in classes. Once a constant is defined, it cannot be changed or undefined.
Constants can only contain scalar data (boolean, integer, float and string). You can define resource constants, but they should be avoided as they can cause unpredictable results.
You can get the value of a constant simply by specifying its name. Unlike variables, you should not put the $ sign in front of a constant. If the constant name is dynamic, you can also use the function constant() to get the value of the constant. Use get_defined_contstants() to get a list of all defined constants.
The above is the detailed content of Definition and use of constants in php. For more information, please follow other related articles on the PHP Chinese website!