W3docs

const

As a PHP developer, you may have used constants to define values that remain unchanged throughout your code. The "const" keyword is a fundamental building block

The PHP const Keyword

A constant is a named value that cannot change while a script runs. The const keyword is one of two ways PHP lets you declare a constant (the other is the define() function). Unlike a variable, a constant has no leading $, and once it is set you cannot reassign or unset() it.

This guide covers what const does, how it differs from define(), where you are allowed to use it, and the common pitfalls that trip people up.

Syntax

You can use const at the top level of a script (a global constant) or inside a class, interface, or trait (a class constant):

const NAME = value;          // global constant
class ClassName {
  const NAME = value;        // class constant, accessed as ClassName::NAME
}

By convention constant names are written in UPPER_SNAKE_CASE. A name must start with a letter or underscore and contain only letters, digits, and underscores.

const vs define()

PHP gives you two tools that look similar but behave differently. Knowing the trade-offs saves debugging time:

Featureconstdefine()
EvaluatedAt compile timeAt run time
Can run conditionally (inside if)NoYes
Works inside a classYes (class constant)No
Name from a variable/expressionNoYes (define($name, ...))
ValueConstant expressions onlyAny expression

Rule of thumb: reach for const for fixed, always-defined values (especially class constants), and define() when the name or value is decided while the program runs.

<?php
// define() can be conditional; const cannot.
if (!defined('ENVIRONMENT')) {
  define('ENVIRONMENT', 'production');
}

// This would be a fatal parse error — const cannot live inside an if-block:
// if (true) { const FOO = 1; }

See the dedicated define() chapter and the PHP constants overview for more.

Examples

Class constant and global constant

<?php

// Example 1 — a class constant referenced with self::
class Circle
{
  const PI = 3.14;
  public $radius;

  public function __construct($radius)
  {
    $this->radius = $radius;
  }

  public function getArea()
  {
    return self::PI * $this->radius * $this->radius;
  }
}

$myCircle = new Circle(5);
echo "Area of circle: " . $myCircle->getArea() . PHP_EOL;

// Output: Area of circle: 78.5

// Example 2 — a global constant
const MY_NAME = "John";
echo "My name is " . MY_NAME;

// Output: My name is John

You read a class constant with the :: (scope resolution) operator — self::PI from inside the class, Circle::PI from outside. A global constant is used by name with no $. For more on classes, see PHP classes and objects and the class constants chapter.

Constant expressions and arrays

A const value must be a constant expression — something PHP can evaluate without running any code. You may use literals, operators, and other already-defined constants, and (since PHP 5.6) the result can be an array.

<?php
const SECONDS_PER_MINUTE = 60;
const SECONDS_PER_HOUR   = SECONDS_PER_MINUTE * 60;  // built from another const
const ALLOWED_ROLES      = ['admin', 'editor', 'viewer'];

echo SECONDS_PER_HOUR . PHP_EOL;       // 3600
echo ALLOWED_ROLES[1] . PHP_EOL;       // editor

Function calls and object instances are not allowed in a const value because they cannot be resolved at compile time.

Class constants: visibility, interfaces, and final

Class constants belong to the class, not to any single object, so you do not need an instance to read them. Since PHP 7.1 you can also give them a visibility modifier:

<?php
interface HasStatus
{
  // Interface constants are always public.
  const DEFAULT_STATUS = 'pending';
}

class Order implements HasStatus
{
  public const TAX_RATE   = 0.2;   // readable everywhere
  protected const MAX_QTY = 99;    // this class + subclasses
  private const SECRET    = 'x';   // this class only

  public function status(): string
  {
    return self::DEFAULT_STATUS;   // inherited from the interface
  }
}

echo Order::TAX_RATE . PHP_EOL;        // 0.2
echo (new Order())->status() . PHP_EOL; // pending

Interfaces can declare constants too (always public) — see PHP interfaces. A class constant can be marked final (PHP 8.1+) to stop subclasses from overriding it.

Common gotchas

  • No $ on a constant. echo MY_NAME; works; echo $MY_NAME; looks for a variable and fails.
  • Cannot be changed or unset. Reassigning a constant is a fatal error; unset() does not work on constants.
  • Compile-time only. You cannot wrap const in an if, loop, or function based on runtime data — use define() for that.
  • Constants are global in scope. A global const is visible inside functions without global, unlike a normal variable.

Benefits

  • Readability: a named constant such as TAX_RATE documents intent far better than a magic number.
  • Maintainability: change a value in one place instead of hunting for every literal.
  • Safety: the value is read-only, so it cannot be overwritten by accident anywhere in the codebase.

Conclusion

The const keyword defines compile-time constants — both global and inside classes — that stay fixed for the life of a script. Use it for fixed values you always know up front, prefer class constants for values that belong to a type, and switch to define() when you need a constant created conditionally or with a dynamic name. To go deeper, continue with the PHP constants and class constants chapters.

Practice

Practice
In PHP, which of the following statements are true about constants?
In PHP, which of the following statements are true about constants?
Was this page helpful?