Constants, like variables, store a certain value, only unlike variables, the value of constants can be set only once, and then we can no longer change it. Constants are usually defined to store values that must remain the same throughout the duration of the script.
const operator
The const operator is used to define a constant, and the dollar sign $ (unlike variables) is not used in the name of the constant.
<?php const PI = 3.14; echo PI; ?>
Usually, the names of constants use capital characters, but this is a convention.
After defining a constant, we can use it just like a normal variable.
PHP allows you to set constant values based on evaluated expressions:
<?php const PI = 2.1415 + 1; echo PI; // 3.1415 ?>
The only exception is that we cannot change the value of the constant. That is, an expression PI = 3.1415; that should change the value of a constant will not work.
define function
You can also use the define() function to define a constant, which has the following form:
define(string $name, string $value)
The parameter $namepasses the name of the constant, and the parameter $value- its value. The value of a constant can represent a type int, float, string, bool, null, or array.
For example, let’s define a numeric constant:
<?php define("NUMBER", 22); echo NUMBER; // 22 ?>
Magic Constants
In addition to the constants created by the programmer, PHP has several more so-called “magic” constants that are in the default language:
- __FILE__ : stores the full path and name of the current file
- __LINE__ : stores the current line number that the interpreter is processing
- __DIR__ : stores the directory of the current file
- __FUNCTION__ : name of the function being processed
- __CLASS__ : current class name
- __TRAIT__ : name of the current trait
- __METHOD__: name of the method being processed
- __NAMESPACE__ : name of the current namespace
- ::class : full name of the current class
For example, let’s print the current executable line and file name:
<?php echo "String " . __LINE__ . " in file " . __FILE__; ?>
Checking for the Existence of a Constant
To check if a constant is defined, we can use the bool-defined (string $name) function. If a constant $ name is defined, then the function will return a value true:
<?php const PI = 3.14; if (!defined("PI")) define("PI", 3.14); else echo "PI constant already defined"; ?>