Justification: Used to store an identifier for a data that does not change and does not want to change.
Constant naming rules, the same variable, but it is customary to say that constant names are often used in "all uppercase" form.
Definition form
- Use the Define () function to define
- Use form: Define ("constant name", constant value);
- Recommended common names use all capitals
- Use the const syntax to define
- Use form: const constant name = constant value;
- However, the const syntax can only be used in the top-most code field (cannot be in curly braces)
- That is, the const syntax cannot be used in a function or in a conditional statement or in other statements that represent a "range"
form of Use:
(1) Direct use of the name
(2) or using the constant () function: constant ("constant name")
The difference between a variable and a constant:
- The definition forms are different:
- Use different form: constant without $ symbol
- Varying degrees of variability: values of constants cannot be changed and constants cannot be destroyed
- Different scopes: constants have a super global scope (functions can be used directly inside and outside the function)
- Available types are different: constants can only store scalar types: int,float,string,bool
To determine whether a constant exists: defined ()
The result of the judgment is a Boolean value.
Common form: if (defined (a constant name) = = False) {... You can define the constant here;}
In fact, this can be:
$result = defined (a constant name); The result is true or false
Use an undefined constant (special case):
Using an undefined constant will report an error (notice error)--As with an undefined variable--not recommended, of course.
But:
PHP, you get an unexpected result: it seems that the constant exists, and the value of the constant is that name.
Magic constants:
A magic constant is a constant whose value changes with a certain condition (environment), form and usage, but in fact, its value changes.
- For example: __dir__ (the directory where the current page file is located), __file__ (current Web page file), __line__ (current line)
- Magic constants are actually similar variables whose values change with different codes and are not case-sensitive
- Reference manual "Language Reference" constant) Magic constant
Results show:
PHP, Constants and Magic constants