ZetCode

PHP const Keyword

last modified November 25, 2026

The PHP const keyword declares a named value that cannot change. It works at the top level of a file and inside classes, interfaces, traits, and enums, where it becomes a class constant reached through the scope resolution operator.

This article covers top-level and class constants, visibility, constant expressions, typed constants added in PHP 8.3, interface and final constants, and the difference between const and define().

Basic definitions

A constant is an identifier for a fixed value. It is written without the $ prefix, it is case-sensitive, and it cannot be reassigned. Top-level constants are available in every scope, so a function does not need global or a parameter to read one. Declaring the same top-level constant twice is a warning in PHP 8.5 and will become an error in PHP 9.

const is resolved while the file is compiled. That makes it fast and allows it in constant expressions, but it also means the declaration must sit in the outermost scope or in a class body, and its value cannot depend on run-time data.

define() is a function call, so it runs when execution reaches it. Use define() when the value is computed at run time or the declaration is conditional, and const for everything that is known from the source. The PHP namespaces article shows how top-level constants are resolved inside a namespace.

A top-level constant

The simplest use is a value that several parts of a script share, such as a tax rate.

const_basic.php
<?php

declare(strict_types=1);

const TAX_RATE = 0.20;

$price = 50.0;
$tax = $price * TAX_RATE;

echo "Price: ", $price, "\n";
echo "Tax: ", $tax, "\n";
echo "Total: ", $price + $tax, "\n";

TAX_RATE is written like a variable but without the dollar sign. The calculation reads it directly, and no assignment to it exists anywhere in the file. If a later line tried TAX_RATE = 0.25;, the file would not compile. Since the value is a float, the prices print without a trailing zero.

$ php const_basic.php
Price: 50
Tax: 10
Total: 60

Class constants

A constant declared inside a class belongs to the class rather than to an instance. It is reached with ClassName::NAME, or with self::NAME from inside the class.

const_class.php
<?php

declare(strict_types=1);

class Invoice
{
    public const TAX_RATE = 0.20;

    public function __construct(private float $net)
    {
    }

    public function gross(): float
    {
        return $this->net * (1 + self::TAX_RATE);
    }
}

$invoice = new Invoice(50.0);

echo "Tax rate: ", Invoice::TAX_RATE, "\n";
echo "Gross: ", $invoice->gross(), "\n";

Invoice::TAX_RATE needs no object, because the rate is the same for every invoice. The method reads it as self::TAX_RATE, and the constructor parameter is a normal promoted property. A class constant is a good home for a value that describes the class, such as a version, a table name, or a limit.

$ php const_class.php
Tax rate: 0.2
Gross: 60

Visibility on constants

Class constants accept the same visibility modifiers as properties and methods. A private constant is an internal detail, protected is available to subclasses, and public is the default.

const_visibility.php
<?php

declare(strict_types=1);

class Connection
{
    private const DSN = "sqlite::memory:";
    protected const TIMEOUT = 5;

    public function dsn(): string
    {
        return self::DSN;
    }
}

$connection = new Connection();
echo $connection->dsn(), "\n";

try {
    echo Connection::DSN, "\n";
} catch (Error $e) {
    echo get_class($e), ": ", $e->getMessage(), "\n";
}

The public method returns the DSN, while the direct access Connection::DSN from outside fails with Cannot access private constant. The protected TIMEOUT would be reachable from a subclass but not from the calling code. Hiding constants is useful when they are implementation details rather than part of the published API.

$ php const_visibility.php
sqlite::memory:
Error: Cannot access private constant Connection::DSN

Constant expressions

The value of a constant may be an expression built from literals, other constants, and a small set of operators. PHP evaluates it at compile time, so the expression cannot call a function or read a variable.

const_expressions.php
<?php

declare(strict_types=1);

const SECONDS_PER_MINUTE = 60;
const SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE;
const SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR;
const WORK_WEEK = 5 * SECONDS_PER_DAY;

echo SECONDS_PER_DAY, "\n";
echo WORK_WEEK, "\n";

Each constant is defined in terms of the previous one, which documents the arithmetic instead of hiding it in a bare number. The expressions are evaluated once, when the file is compiled, and the running code only reads the results. Function calls are not allowed in this position, so const DAY = 24 * 60 * 60; is fine while const DAY = time(); is a compile error.

$ php const_expressions.php
86400
432000

Typed constants

Since PHP 8.3 a class constant may declare a type. The value is then checked against that type when the class is compiled, which catches a wrong literal immediately.

const_typed.php
<?php

declare(strict_types=1);

class Api
{
    public const string VERSION = "2.1";
    public const int MAX_RETRIES = 3;
}

echo Api::VERSION, "\n";
echo Api::MAX_RETRIES, "\n";

VERSION is a string and MAX_RETRIES an integer, and both are enforced. A wrong value does not wait for the constant to be used: the declaration itself fails, as the next example shows. Typed constants are available on classes, interfaces, traits, and enums, and the type may be a union such as int|string.

$ php const_typed.php
2.1
3

A typed constant with the wrong value

The type check happens at compile time, so assigning a string to an int constant stops the file before any statement runs.

const_typed_error.php
<?php

declare(strict_types=1);

class Api
{
    public const int MAX_RETRIES = "three";
}

The message names the constant, the expected type, and the actual one: Cannot use string as value for class constant Api::MAX_RETRIES of type int. Without the declared type, PHP would have accepted the string and the mistake would surface only when the value was used in arithmetic. The union types article covers the type syntax.

$ php const_typed_error.php
Fatal error: Cannot use string as value for class constant Api::MAX_RETRIES of type int in /app/const_typed_error.php on line 7
Stack trace:
#0 {main}

Interface constants

An interface can declare constants, and every implementing class inherits them. This is a natural home for a fixed set of codes that belong to a contract.

const_interface.php
<?php

declare(strict_types=1);

interface HttpStatus
{
    public const OK = 200;
    public const NOT_FOUND = 404;
}

function describe(int $status): string
{
    return match ($status) {
        HttpStatus::OK => "OK",
        HttpStatus::NOT_FOUND => "Not Found",
        default => "Unknown status",
    };
}

echo describe(HttpStatus::OK), "\n";
echo describe(500), "\n";

The function uses HttpStatus::OK and HttpStatus::NOT_FOUND instead of bare numbers, so the meaning is visible at the call site. A class that implements the interface inherits the constants and can refer to them as self::OK. The interface keeps the codes together under one name and makes them available to every implementation. If a value must not be replaced, declare it final, as the next section shows. The interface keyword article covers the contract itself.

$ php const_interface.php
OK
Unknown status

Final constants

Since PHP 8.1 a constant can be marked final. A child class may not redefine it, which protects a value that the parent's methods rely on.

const_final.php
<?php

declare(strict_types=1);

class Base
{
    final public const NAME = "base";
}

class Child extends Base
{
    public const NAME = "child";
}

PHP reports Child::NAME cannot override final constant Base::NAME and refuses to compile the child. Without final, the child's value would silently replace the parent's, and any inherited method that reads NAME would behave differently. The final keyword article covers the same modifier on classes and methods.

$ php const_final.php
Fatal error: Child::NAME cannot override final constant Base::NAME in /app/const_final.php on line 10
Stack trace:
#0 {main}

const versus define()

define() creates a constant at run time, so it works inside a condition and can use a computed value. The defined() function tests whether a name exists.

const_define.php
<?php

declare(strict_types=1);

const MODE = "cli";

define("DEBUG", true);
define("STAGE", MODE === "cli" ? "local" : "remote");

if (PHP_SAPI === "cli") {
    define("RUNNER", "command line");
}

echo STAGE, "\n";
echo defined("RUNNER") ? RUNNER : "no runner", "\n";

STAGE is computed from MODE when the call runs, and RUNNER is defined only inside the branch that matches. Both are readable as ordinary constants afterwards. define() always creates a top-level constant, even when it is called from inside a class, so it cannot add a class constant. Prefer const for values that are fixed in the source, because the compiler can check them and tools can find them.

$ php const_define.php
local
command line

const must be at the top level

Because const is a compile-time declaration, it is not a statement that can appear inside a block or a function. A conditional declaration must use define().

const_scope_error.php
<?php

declare(strict_types=1);

if (true) {
    const LIMIT = 10;
}

echo LIMIT, "\n";

The parser stops at the keyword with syntax error, unexpected token "const". The same restriction applies inside functions and methods. This is the practical reason the previous section used define() inside an if: the value had to be decided at run time, and const cannot do that.

$ php const_scope_error.php
Parse error: syntax error, unexpected token "const" in /app/const_scope_error.php on line 6

Best practices

Use constants for values that are fixed by the problem domain, and give them a home close to the code that owns them.

The PHP enum article shows the modern alternative for a closed set of named values, and PHP use keyword explains importing constants from a namespace.

Source

PHP manual: constants

PHP manual: class constants

PHP manual: define

This article covered the PHP const keyword: top-level and class constants, visibility, constant expressions, typed constants, interface and final constants, the difference from define(), and the rule that const belongs to the outermost scope. Continue with PHP enum for named cases, or read PHP namespace keyword for scoping.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all PHP tutorials.