Class Constants are fixed values that are defined as part of a class definition. Unlike static properties, their values cannot be changed once they are declared. They are perfect for defining status codes, limits, configuration settings, or fixed ratios related to that class.
1. Defining a Class Constant
- Keyword: You define a Class Constant using the
constkeyword. - Naming Convention: By convention, Class Constants are always named in uppercase (often with underscores for spaces, e.g.,
MAX_ATTEMPTS). - Access Modifier: Class Constants are implicitly public and cannot have explicit access modifiers (
public,protected,private).
Example: Defining Status Codesphp oop class constants const
<?php
class UserStatus {
// These values cannot be changed during the script's execution
const ACTIVE = 1;
const PENDING = 2;
const BANNED = 3;
const MAX_LOGIN_ATTEMPTS = 5;
}
?>
2. Accessing Class Constants
Class Constants are static (belong to the class, not the object), so they are accessed using the Scope Resolution Operator (::), not the object operator (->).
A. Accessing Outside the Class
You access a constant using the Class Name followed by the double colon operator (::) and the constant name.
PHP
<?php
// Check the current status against a constant value
$userCurrentStatus = 2; // Assume 2 means PENDING
if ($userCurrentStatus === UserStatus::PENDING) {
echo "User profile is waiting for administrator approval (Code: " . UserStatus::PENDING . ").";
} else {
echo "Current status: " . $userCurrentStatus;
}
// Output: User profile is waiting for administrator approval (Code: 2).
?>
B. Accessing Inside the Class
Inside the class, you access the constant using the self:: keyword, followed by the constant name.
<?php
class Login {
const MAX_ATTEMPTS = 5;
public static function checkAttempts($currentAttempts) {
if ($currentAttempts >= self::MAX_ATTEMPTS) {
return "Account locked. Maximum attempts reached.";
} else {
return "Attempts remaining: " . (self::MAX_ATTEMPTS - $currentAttempts);
}
}
}
echo Login::checkAttempts(3);
// Output: Attempts remaining: 2
?>
3. Class Constants vs. Static Properties
| Feature | Class Constant (const) | Static Property (static $name) |
| Declaration | const NAME = 'value'; | public static $name = 'value'; |
| Mutability | Cannot be changed (Read-only). | Can be changed during script execution. |
| Access Sign | Accessed without $: ClassName::NAME | Accessed with $: ClassName::$name |
| Use Case | Fixed values (status codes, fixed rates, pi). | Shared, changeable data (counters, temporary configuration). |
Because constants are fixed, they are often safer for defining critical limits and reference values than static properties.
⏭️ Next Steps
You’ve completed the discussion on defining fixed values. The final pending OOP topic is Iterables. This is a broad topic that ensures your data structures can work correctly with standard PHP loops.
