PHP const Keyword

PHP

PHP const Keyword - Class Constants

The const keyword in PHP is used to define class constants—immutable values that are associated with a class itself rather than any individual instance. These constants provide a way to store fixed values which cannot be changed after declaration, improving code reliability and readability.

Prerequisites

  • Basic understanding of PHP syntax
  • Familiarity with PHP classes and objects
  • PHP version 5.3 or higher (const keyword usage in classes available since PHP 5.3)
  • A working PHP development environment (local setup or server)

Setup Steps

  1. Ensure PHP is installed and running on your system. You can verify this by running:

    php -v
  2. Create a new PHP file (e.g., const-example.php) for your practice.

  3. Open your PHP IDE or text editor and prepare to write a class with constants.

  4. Run your PHP script via command line or browser to test the output.

Understanding the PHP const Keyword

Using const, you can declare constant values inside a class. These values:

  • Are automatically public — accessible anywhere without needing an instance
  • Cannot be changed once declared (immutable)
  • Belong to the class rather than any particular object

Basic Syntax of Class Constants

class ClassName {
    const CONSTANT_NAME = value;
}

Examples of Using const in PHP Classes

Example 1: Defining and Accessing Class Constants

<?php
class Vehicle {
    const WHEELS = 4;
    const MAX_SPEED = 120;
}

// Access via class name and scope resolution operator
echo Vehicle::WHEELS;     // Outputs: 4
echo Vehicle::MAX_SPEED;  // Outputs: 120
?>

Explanation: We defined two constants inside the Vehicle class. These constants can be accessed using the :: operator without instantiating the class.

Example 2: Using Constants Inside Class Methods

<?php
class Circle {
    const PI = 3.14159;

    public function getCircumference($radius) {
        return 2 * self::PI * $radius;
    }
}

$circle = new Circle();
echo $circle->getCircumference(5);  // Outputs: 31.4159
?>

Explanation: Inside class methods, you can reference constants using self::CONSTANT_NAME. This example calculates the circumference using the constant PI.

Example 3: Difference Between const and define()

<?php
// Using const inside a class
class Config {
    const VERSION = '1.0.0';
}

// Global constant using define()
define('APP_NAME', 'MyApp');

echo Config::VERSION; // Works fine
echo APP_NAME;        // Works fine

// However, define() cannot be used inside classes to define class constants.

?>

Best Practices When Using const in PHP

  • Name constants in uppercase letters separated by underscores (e.g., MAX_COUNT). This is a widely followed convention.
  • Use const within classes to define values that should never change and are relevant to the class context.
  • Access constants using ClassName::CONSTANT or self::CONSTANT inside class methods.
  • Use constants instead of hardcoded "magic values" for better maintainability and readability.
  • Use const rather than define() inside classes, since define() does not work for class constants.
  • Remember, constants cannot hold dynamic or computed values—they must be assigned a constant expression at declaration time.

Common Mistakes with PHP const

  • Trying to assign a value that is not a constant expression (e.g., using function return, variables):
    const INVALID = strtolower('abc'); // Won't work
  • Attempting to change constant values after declaration:
    ClassName::CONSTANT = 'new value'; // Fatal error
  • Using const outside of a class or interface post PHP 5.3. Note that starting PHP 7, you can also use const at the top-level scope as an alternative to define().
  • Accessing the constant via an instance rather than the class:
    $obj = new ClassName();
    echo $obj->CONSTANT; // Invalid; should be ClassName::CONSTANT
  • Confusing const with variables—constants don’t use a dollar sign $, but variables do.

Interview Questions

Junior-Level Questions

  • Q1: What does the PHP const keyword do inside a class?

    A: It defines a constant value associated with the class, which cannot be changed after declaration.

  • Q2: How do you access a class constant in PHP?

    A: Using ClassName::CONSTANT_NAME syntax.

  • Q3: Can you change the value of a class constant during runtime?

    A: No, class constants defined with const are immutable.

  • Q4: Inside a class method, how do you reference a class constant?

    A: By using self::CONSTANT_NAME.

  • Q5: Do you use a dollar sign $ when declaring a constant with const?

    A: No, constants do not use a dollar sign.

Mid-Level Questions

  • Q1: What types of values can be assigned to class constants using const?

    A: Only constant expressions such as scalars (int, float, string, bool), arrays (from PHP 5.6+), or constants. No runtime expressions.

  • Q2: How is a class constant different from a static variable?

    A: A class constant is immutable and cannot be changed, whereas static variables are mutable and can store dynamic data.

  • Q3: Can you declare class constants as private or protected?

    A: Prior to PHP 7.1, all constants were public by default. Starting PHP 7.1, you can specify visibility (private/protected).

  • Q4: Can you use const outside of a class?

    A: Yes, starting PHP 7, const can be used at the top-level scope similar to define().

  • Q5: Why is it recommended to use class constants instead of hardcoding values?

    A: To improve code maintainability, readability, and avoid "magic numbers" or strings scattered across the code.

Senior-Level Questions

  • Q1: Explain how late static binding affects the access of class constants in PHP inheritance.

    A: Late static binding allows referencing the constant in the called class context using static::CONSTANT instead of self::CONSTANT, enabling polymorphic behavior.

  • Q2: What changes were introduced in PHP 7.1 regarding class constants?

    A: PHP 7.1 introduced visibility modifiers (public, protected, private) for class constants.

  • Q3: How would you organize and structure class constants in a project with many domain constants?

    A: Group related constants logically into multiple classes or interfaces, use namespaces, and document constants clearly to maintain organization and clarity.

  • Q4: Can constants be autoloaded using SPL autoloaders in PHP classes?

    A: Yes, because constants are part of class definitions, they are available once the class is autoloaded.

  • Q5: Discuss the limitations of using const to define complex constant types like objects.

    A: Class constants must be initialized with constant values; you cannot assign objects or resources to const. For complex immutable objects, use static readonly properties (from PHP 8.1).

FAQ - Frequently Asked Questions

Q: Can I change a constant after it is declared?

A: No. Constants defined with const are immutable and cannot be modified once set.

Q: Are class constants inherited by child classes?

A: Yes, class constants are inherited by subclasses and can be accessed with the subclass name or via parent::.

Q: Can I use expressions when defining constants?

A: Only constant expressions are allowed, such as scalar values or arrays (in PHP 5.6+). Functions or variables cannot be used during declaration.

Q: What's the difference between const and define()?

const is used to declare constants inside classes and namespaces, supports early binding and type checks, whereas define() defines global constants at runtime and cannot be used inside classes.

Q: Can class constants have visibility modifiers?

Starting PHP 7.1, yes. You can specify public, protected, or private visibility for class constants.

Conclusion

The PHP const keyword is a powerful feature to define immutable values tied to a class rather than instances. Using class constants enhances code clarity, enforces immutability, and provides a centralized way to manage fixed values. Proper understanding and usage of the const keyword is essential for writing robust, maintainable PHP object-oriented applications.