Back to results for “OOP”
PHP › Constants & Superglobals

What is the difference between class constants and global constants, and how do you define and access a constant within a class?

Intermediate

Answer

A class constant is defined within a class using the const keyword and is accessed using the scope resolution operator alongside the class name, scoping the constant specifically to that class rather than making it globally available throughout the entire application, which is generally preferred for values that are conceptually tied to a specific class, such as a status code relevant only to an order processing class.
class Order {
    const STATUS_PENDING = 'pending';
    const STATUS_SHIPPED = 'shipped';
}
echo Order::STATUS_PENDING;
Real-world example An order management system defines status related constants directly within the Order class itself, clearly scoping those values to orders specifically rather than polluting the global namespace with generically named constants.

Common follow-ups: Can a class constant's value depend on another constant or a class property?;How do class constants differ from PHP 8.1's readonly properties for representing fixed values?