Home > Article > Backend Development > How to define constants in PHP7.0?
In PHP, the definition of constants can provide some specific immutable values for your project. Prior to PHP 7.0, constants were defined through the define() function. However, in PHP7.0, constants can be defined using the const keyword.
This article will introduce how to define constants in PHP7.0.
Step one: Use const to define constants
Relative to the define() function, it is simpler to use the const keyword to define constants.
Let's take a look at an example:
<?php const PI = 3.14; echo PI; ?>
Output:
3.14
In the above example, we use the const keyword to define a constant named PI, and Its setting is 3.14. Then, we printed the value of this constant.
Please note that unlike the define() function, when defining a constant using the const keyword, you do not need to pass the string name of the constant. Instead, it defines constant names and values directly after const.
Step 2: Use constants
After you define a constant, you can use it anywhere in the project. Here is a simple example:
<?php const FRUIT = "apple"; echo FRUIT; ?>
Output:
apple
In the above example, we defined a constant named FRUIT using the const keyword and set it to "apple ". Then, we print the value of this constant on the next line of code.
Step 3: The value of the constant must be a constant expression
You must use constants in constant expressions, otherwise a compilation error will occur.
Here is an example of how to use constants in constant expressions:
<?php const HEIGHT = 100; const WIDTH = HEIGHT * 2; echo WIDTH; ?>
Output:
200
In the above example, we first define the HEIGHT constant and Set it to 100. We then use the constant HEIGHT to calculate the value of the constant WIDTH, which is perfectly valid.
Step 4: Name the constant
When you use the const keyword to define a constant in PHP7.0, you must give it a name. The name must comply with the following rules:
Here are some examples of valid constant names:
const SERVER_URL = "http://example.com"; const DEBUG_MODE = true; const MAX_USER_COUNT = 100;
Please note that unlike variable naming convention, in constant naming convention, spaces between words should be replaced by underscores.
Conclusion
In this article, we introduced how to define constants in PHP7.0. Defining constants using the const keyword is simpler than using the define() function. But remember, when defining a constant, its value must be a constant expression.
The above is the detailed content of How to define constants in PHP7.0?. For more information, please follow other related articles on the PHP Chinese website!