How to Declare Constants in PHP Classes

Updated: January 10, 2024 By: Guest Contributor Post a comment

Overview

Working with constants in PHP classes is essential for ensuring immutability and consistency within your objects. This tutorial explores the declaration and utilization of class constants with progressing examples.

Introduction to Constants

Constants are immutable variables which, once defined, cannot change their values during the execution of the script. In the context of classes, they represent fixed values that are inherently associated with a class rather than an instance of the class. Defining constants within classes can be accomplished using the const keyword. Here’s how you can define and access a simple constant:

class MathConstants {
    const PI = 3.14159;
}

echo MathConstants::PI; // Outputs: 3.14159

This basic usage of const within a class allows the value of PI to be accessed statically.

Naming Conventions and Scope

Naming constants in uppercase is a common convention that helps to make them easily distinguishable from class properties or methods. The scope of a constant declared within a class is also crucial to understand – it is accessible anywhere, but always in the context of the class, and immutable regardless of object instantiation.

Visibility Modifiers

As of PHP 7.1, constants can have visibility modifiers much like properties and methods. Here’s how you can define public, protected, and private constants in a PHP class:

class UserStatus {
    public const ACTIVE = 'active';
    protected const PENDING = 'pending';
    private const INACTIVE = 'inactive';
}

// Public constants can be accessed from outside the class.
echo UserStatus::ACTIVE; // Outputs: 'active'

// Protected and private constants cannot be accessed from outside the class.
// The following will result in a fatal error:
// echo UserStatus::PENDING;
// echo UserStatus::INACTIVE;

Visibility serves as access control for class constants, allowing developers to encapsulate the logic-specific values within the class.

Using Class Constants in Methods and Constructors

Constants can be used within class methods or the constructor to provide predefined values. The following example demonstrates a class method utilizing a class constant:

class Circle {
    const PI = 3.14159;

    private $radius;

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

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

$circle = new Circle(10);
echo $circle->circumference(); // Outputs: 62.8318

The circumference() method calculates the circumference of a circle by using the PI constant declared within the same class.

Constants in Interfaces and Abstract Classes

Constants can also be defined within interfaces and abstract classes, which can then be inherited by implementing or extending classes. This ensures that a set of classes share the same constant values.

interface Configurable {
    const TIMEOUT = 30;
}

class ApiClient implements Configurable {
    public function timeout() {
        return self::TIMEOUT;
    }
}

echo (new ApiClient())->timeout(); // Outputs: 30

The ApiClient class implements the Configurable interface and thus inherits the TIMEOUT constant.

Using the define() Function

Though not specific to class constants, it’s worth noting that PHP also supports defining constants using the define() function. While this is not part of class constants’ system, it provides an alternative way to define immutable values at the global scope.

define('APPLICATION_VERSION', '1.0.0');
echo APPLICATION_VERSION; // Outputs: '1.0.0'

Do note that constants defined using define() cannot be accessed through the scope resolution operator (::) in the context of a class.

Best Practices and Uses Cases

Class constants are often used to represent fixed data in utilities classes, configuration values, or status codes. Adhering to principles such as ‘one source of truth’ and encapsulation will guide you to employ class constants efficiently. They should aim to make your code more predictable and maintainable.

class HttpStatusCodes {
    const OK = 200;
    const NOT_FOUND = 404;
    const INTERNAL_SERVER_ERROR = 500;
}

echo HttpStatusCodes::OK; // Outputs: 200

By centralizing HTTP status codes in a single class, you reduce the risk of typos or inconsistent values across your codebase.

Constant Expressions

PHP 5.6 and later versions support constant expressions. This allows for the use of operations in constant declarations, which makes possible dynamically computed constants.

class FileSizes {
    const KB = 1024;
    const MB = self::KB * 1024;
    const GB = self::MB * 1024;
}

echo FileSizes::GB; // Outputs: 1073741824

The above classes use arithmetic operations to define constants via previously declared constants, demonstrating how expressive constant declarations can be.

Conclusion

Using class constants in PHP provides a strong foundation for clean, reliable, and maintainable code by ensuring that certain crucial values remain immutable and widely accessible. Whether you’re defining configuration options, status codes, or mathematical constants, understanding how to properly declare and use class constants is an essential skill for any PHP developer.