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
self::MAX_AMOUNT) { return false; } return true; } } ?>Accessing Class Constants
Class constants are accessed using the Scope Resolution Operator (::):
- From inside the class: Use
self::CONSTANT_NAME. - From outside the class: Use
ClassName::CONSTANT_NAME.
php
Processing transaction..."; } ?>Benefit: Using constants instead of magic strings (raw strings like 'PENDING') makes code safer, easier to refactor, and more readable.