> ## 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.

# PHP Constant

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.

```php theme={"dark"}
// 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);`).

```php theme={"dark"}
$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:

```php theme={"dark"}
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.

```php theme={"dark"}
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.

```php theme={"dark"}
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.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor PHP Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
