Lesson
PHP Class Constants (OOP)
10 min reading
Free CourseClass Constants (const, Visibility Modifiers, self::)
Class constants are immutable values allocated per class definition rather than per object instance. Starting in PHP 7.1, class constants support access visibility modifiers (public const, protected const, private const).
Class Constant Features
- Declared with
constkeyword (Without$sign). - Referenced inside class via
self::CONSTANT_NAME. - Referenced outside class via
ClassName::CONSTANT_NAME. - Value cannot be mutated after definition.
flowchart LR
A["ClassName::API_VERSION"] --> B["Class Constant Evaluation"]
C["self::MAX_RETRY_LIMIT"] --> B
B --> D["Shared Immutable Value Across All Objects"]
Practical Code Example
<?php
declare(strict_types=1);
class PaymentGateway
{
// Public Class Constant (Accessible globally)
public const CURRENCY_USD = "USD";
public const CURRENCY_EUR = "EUR";
// Protected Class Constant (Accessible only in class & subclasses)
protected const API_VERSION = "v2.5";
// Private Class Constant (Encapsulated internally)
private const MAX_RETRIES = 3;
public function processTransaction(float $amount, string $currency): string
{
if (!in_array($currency, [self::CURRENCY_USD, self::CURRENCY_EUR], true)) {
throw new InvalidArgumentException("Unsupported Currency");
}
return "Processing $" . $amount . " " . $currency . " via API " . self::API_VERSION . " (Max Retries: " . self::MAX_RETRIES . ")";
}
}
$gateway = new PaymentGateway();
echo "Supported Currency: " . PaymentGateway::CURRENCY_USD . "
";
echo $gateway->processTransaction(100.0, PaymentGateway::CURRENCY_USD) . "
";
Best Practices
- Always Explicitly State Visibility Modifiers: Declare constants as
public const,protected const, orprivate const. - Use UPPERCASE_SNAKE_CASE Formatting: Follow standard constant naming (
STATUS_ACTIVE,DEFAULT_PORT). - Use
self::for Internal References: Reference class constants internally viaself::CONST_NAMErather than hardcoding values.
Self-Check Challenge
Write a class Status containing public const DRAFT = 'draft'; and access it outside the class using Status::DRAFT!
Save Your Progress
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Enterprise-Grade Security Protocol
Try it Yourself
Experiment with the code from this lesson in our interactive playground.