Back to course

Constants within Classes

PHP: The Complete 0 to Hero Bootcamp

38. Constants within Classes

Class constants are fixed values associated with a class, defined using the const keyword. Like static properties, they belong to the class itself, not the object, and their values cannot change during execution.

Defining Class Constants

Constants are automatically public, static, and do not use the $ prefix.

php

<?php class PaymentProcessor { const STATUS_PENDING = 'PENDING'; const STATUS_COMPLETE = 'COMPLETE'; const MAX_AMOUNT = 10000; public function checkMaxAmount($amount) { if ($amount > self::MAX_AMOUNT) { return false; } return true; } } ?>

Accessing Class Constants

Class constants are accessed using the Scope Resolution Operator (::):

  1. From inside the class: Use self::CONSTANT_NAME.
  2. From outside the class: Use ClassName::CONSTANT_NAME.

php

<?php // Accessing from outside echo "Maximum transaction allowed: " . PaymentProcessor::MAX_AMOUNT; // Output: 10000 // Using the constant within logic $processor = new PaymentProcessor(); $transaction_status = PaymentProcessor::STATUS_PENDING; if ($transaction_status == PaymentProcessor::STATUS_PENDING) { echo "<br>Processing transaction..."; } ?>

Benefit: Using constants instead of magic strings (raw strings like 'PENDING') makes code safer, easier to refactor, and more readable.