Unlike variables, we cannot change the value of a constant after we declare it.

I. How to declare a constant

To declare a constant in PHP, we use a define() or a const keyword.

  • define() function accepts two parameters: name and value.
define("name", "value");

When referencing a constant, we don’t need a dollar sign $.


define("PI", 3.14);
echo PI; // 3.14
  • using const
const STATUS = "paid";

II. Constant name requirement

A constant name

  • must start with a letter or the underscore character.
  • cannot contain any special character.
  • can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
  • is case-sensitive.

III. Check if the constant is defined.

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

IV. Magic constants

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