PHP
Constant use cases
Learn to define configuration values and status codes with class constants.
Constants for configuration and status codes
One of the most common uses of class constants is defining configuration values and status codes.
Example: in an HTTP response class, status codes are defined as constants: class HttpResponse { const int OK = 200; const int NOT_FOUND = 404; const int SERVER_ERROR = 500; }. This avoids magic numbers.
Other examples: log levels (INFO, WARNING, ERROR), roles (ADMIN, USER, GUEST), file modes (READ, WRITE). This pattern is the predecessor of PHP 8.1 enums (BackedEnum).
Enum-like structures
With class constants you can build enum-like structures. Before PHP 8.1 there were no enums, so constants were a common pattern.
Example: class OrderStatus { const string PENDING = 'pending'; const string PAID = 'paid'; const string SHIPPED = 'shipped'; }. An order's status is expressed with a readable constant like OrderStatus::PAID; this is safer than writing the string 'paid' by hand.
This pattern also gives IDE auto-completion and refactoring support.
Exercise HttpResponse class with status code constants
Define an HttpResponse class with const int OK = 200; and const int NOT_FOUND = 404;. Add public function message(int $code): string with if ($code === self::OK) { return 'Success'; } and if ($code === self::NOT_FOUND) { return 'Not found'; }, finally return 'Unknown'. Then create $resp = new HttpResponse() and print echo $resp->message(HttpResponse::OK) . "\n". (Expected output: Success)
Show example solution
string { if ($code === self::OK) { return 'Success'; } if ($code === self::NOT_FOUND) { return 'Not found'; } return 'Unknown'; } } then $resp = new HttpResponse(); echo $resp->message(HttpResponse::OK) . "\n";
Example solution:
<?php
// Define an HttpResponse class
class HttpResponse {
const int OK = 200;
const int NOT_FOUND = 404;
public function message(int $code): string {
if ($code === self::OK) {
return 'Success';
}
if ($code === self::NOT_FOUND) {
return 'Not found';
}
return 'Unknown';
}
}
$resp = new HttpResponse();
echo $resp->message(HttpResponse::OK) . "
";
Test yourself
-
Which is a good use case for a class constant?
- The user's name (different per instance)
- HTTP status codes (200, 404, 500)
- A temporary computation result
- A database query result
Show answer
HTTP status codes (200, 404, 500) — Correct. HTTP status codes are immutable values; a class constant is ideal.
-
Define an HTTP status code constant
class HttpResponse {
____
}
Show answer
class HttpResponse {
const int NOT_FOUND = 404;
}
-
Match the class constant patterns
- const int OK = 200
- HTTP status code
- const string PENDING = 'pending'
- Enum-like status
- const float PI = 3.14
- Mathematical constant
- const array LEVELS = ['INFO','ERROR']
- Log levels
Next lesson: Summary - Class constants