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).
const keyword (Without $ sign).self::CONSTANT_NAME.ClassName::CONSTANT_NAME.flowchart LR
A["ClassName::API_VERSION"] --> B["Class Constant Evaluation"]
C["self::MAX_RETRY_LIMIT"] --> B
B --> D["Shared Immutable Value Across All Objects"]
<?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) . "
";
public const, protected const, or private const.STATUS_ACTIVE, DEFAULT_PORT).self:: for Internal References: Reference class constants internally via self::CONST_NAME rather than hardcoding values.Write a class Status containing public const DRAFT = 'draft'; and access it outside the class using Status::DRAFT!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.