PHP OOP - Class Constants

In PHP Object-Oriented Programming (OOP), class constants are immutable values defined within a class using the const keyword. They are useful for defining values that should not change and are specific to the class's context.

Syntax:

class MyClass { const MY_CONSTANT = 'Some value'; }

Accessing Class Constants:

Class constants are accessed using the scope resolution operator :::

echo MyClass::MY_CONSTANT;

You can also access them from within the class using self:::

class MyClass { const GREETING = 'Hello'; public function sayHello() { echo self::GREETING; } }

Inheritance with Constants:

Child classes can inherit constants, but they cannot override them directly:

class ParentClass { const VERSION = '1.0'; } class ChildClass extends ParentClass {} echo ChildClass::VERSION; // Outputs: 1.0

If a child defines a constant with the same name, it doesn't override the parent — it simply defines a new constant for the child class.

Example:

class Math { const PI = 3.14159; public function getCircleArea($radius) { return self::PI * $radius * $radius; } }