Interface Constants
Interfaces can define constants that implementing classes inherit. They cannot be overridden by implementing classes (as of PHP 8.1, they can be declared final).
Interfaces can define constants that implementing classes inherit. They cannot be overridden by implementing classes (as of PHP 8.1, they can be declared final).
<?php
interface StatusCodes {
const OK = 200;
const NOT_FOUND = 404;
const SERVER_ERROR = 500;
const CREATED = 201;
const NO_CONTENT = 204;
}
class ApiResponse implements StatusCodes {
public function ok(array $data): array {
return ["status" => self::OK, "data" => $data];
}
public function notFound(string $msg): array {
return ["status" => self::NOT_FOUND, "error" => $msg];
}
}
echo ApiResponse::OK; // 200
echo StatusCodes::NOT_FOUND; // 404
Group related constants in interfaces to create named constant sets — all implementing classes get them automatically.