Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A constant in PHP is an identifier for a simple value that remains immutable throughout the execution of a script. Unlike variables, constants do not use the $ prefix and, once defined, their assigned value cannot be reassigned, modified, or undefined. Constants can be assigned scalar data types (boolean, integer, float, string), arrays, or the special null value. Although technically possible, assigning resource types to constants is strongly discouraged by the PHP manual due to unpredictable behavior.

Instantiation Syntax

PHP provides two distinct mechanisms for defining constants: the define() function and the const keyword.
// Using the define() function
define('MAX_CONNECTIONS', 100);
define('SUPPORTED_LOCALES', ['en_US', 'es_ES', 'fr_FR']);

// Using the const keyword
const API_VERSION = 'v2.1.0';
const TIMEOUT_SECONDS = 30;

define() vs. const

While both create constants, their evaluation context and scoping rules differ significantly:
  • Evaluation Time:
    • const constructs are evaluated at compile time. They must be declared at the top-level scope or within a class/interface. They cannot be declared inside functions, loops, if statements, or try/catch blocks.
    • define() is a function evaluated at runtime. It can be invoked conditionally within control structures.
  • Namespacing:
    • const automatically respects the current namespace.
    • define() requires the fully qualified namespace to be passed as part of the string name (e.g., define('MyNamespace\MY_CONST', 1);).
$condition = true;

// Valid: define() at runtime inside a control structure
if ($condition) {
    define('DYNAMIC_CONST', true); 
}

// Invalid: const cannot be used in block scope
/*
if ($condition) {
    const INVALID_CONST = true; // Throws Parse error
}
*/

Naming Rules

  • Constant names must start with a letter or underscore, followed by any number of letters, numbers, or underscores.
  • The internal regular expression for a valid constant name is: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$
  • Constants are case-sensitive. (Note: The ability to create case-insensitive constants via the third parameter of define() was deprecated in PHP 7.3 and removed entirely in PHP 8.0).
  • By standard convention, constant identifiers are written in UPPER_SNAKE_CASE.

Scope, Existence, and Dynamic Access

Constants are inherently global. Once defined, they can be accessed from anywhere in the script—inside functions, classes, or closures—without requiring the global keyword or scope resolution operators (unless they are class constants). To check if a constant has been defined, PHP provides the defined() function. To retrieve a constant’s value dynamically when the name is stored in a variable, use the constant() function:
define('ENVIRONMENT', 'production');

// Check if a constant exists
if (defined('ENVIRONMENT')) {
    $constName = 'ENVIRONMENT';
    
    // Retrieve value dynamically
    echo constant($constName); // Outputs: production
}

Undefined Constants

Attempting to access a constant that has not been defined results in a fatal error in modern PHP. As of PHP 8.0, accessing an undefined constant throws an Error exception. Prior to PHP 8.0, the engine emitted a warning and fell back to evaluating the constant as a string literal of its own name.
try {
    echo MISSING_CONST;
} catch (Error $e) {
    echo $e->getMessage(); // Outputs: Undefined constant "MISSING_CONST"
}

Class Constants

Constants can be scoped to a specific class, interface, or trait using the const keyword. These are allocated once per class, not per instance, and are accessed via the Scope Resolution Operator (::). Recent versions of PHP have significantly expanded class constant capabilities:
  • Visibility Modifiers (PHP 7.1+): Class constants support public, protected, and private visibility.
  • Final Constants (PHP 8.1+): The final modifier prevents child classes from overriding the constant.
  • Typed Constants (PHP 8.3+): Type declarations can be specified to enforce the data type of the constant.
class Database {
    // Visibility modifier
    private const MAX_RETRIES = 3;
    
    // Final class constant (cannot be overridden)
    final public const DEFAULT_PORT = 3306;
    
    // Typed class constant
    public const string CONNECTION_DRIVER = 'mysql';
}

echo Database::DEFAULT_PORT; // Outputs: 3306

Magic Constants

The PHP engine implements several “magic constants” (e.g., __LINE__, __FILE__, __DIR__, __CLASS__). While syntactically treated as constants, they are technically compile-time tokens. Their values are not static; they resolve dynamically based on the lexical context of where they are used in the parser.
Master PHP with Deep Grasping Methodology!Learn More