PHP Constants

Constants hold a value that cannot change once defined.

Syntaxdefine("NAME", value); const NAME = value;

A constant is like a variable, except its value can never be changed after it is set. You do not use the $ sign with constants.

Two ways to define

  • The define() function.
  • The const keyword.

By convention constant names are written in UPPERCASE.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • App-wide settings that must never change at runtime β€” site name, version.
  • Fixed limits and magic numbers such as MAX_UPLOAD or TAX_RATE.
  • Environment flags read in many places, e.g. IS_PRODUCTION.

More examples

define() vs const

define() runs at runtime; const is evaluated at compile time and must sit at the top level.

Example Β· php
<?php
define("SITE_NAME", "SoundsCode");
const VERSION = "2.1";
echo SITE_NAME . " v" . VERSION;

Constants inside a class

Class constants belong to the class and are read with self::PI or Circle::PI.

Example Β· php
<?php
class Circle {
    const PI = 3.14159;
    public function area($r) {
        return self::PI * $r * $r;
    }
}
echo (new Circle)->area(2);

Guard with defined()

defined() checks whether a constant exists before you use or redefine it.

Example Β· php
<?php
if (!defined("MODE")) {
    define("MODE", "live");
}
echo defined("MODE") ? MODE : "unset";

Discussion

  • Be the first to comment on this lesson.
PHP Constants β€” PHP | SoundsCode