Unlike variables, we cannot change the value of a constant after we declare it.
To declare a constant in PHP, we use a define()
or a const
keyword.
define("name", "value");
When referencing a constant, we don’t need a dollar sign $.
Example
define("PI", 3.14);
echo PI; // 3.14
const STATUS = "paid";
A constant name
We can use the function defined() to check if a constant has been defined.
If it returns 1, it means true.
define("STATUS", "paid");
echo defined("STATUS"); // Output: 1
Magic constants can change values depending on where they are used.
For example, __LINE__
contains the value of the line number it is used.
echo __LINE__;
Learn more: Magic constants