SyntaxStudy
Sign Up
PHP Constants & Final Classes
PHP Intermediate 8 min read

Constants & Final Classes

Class constants define values that cannot change and are associated with the class rather than instances. The final keyword prevents a class from being extended or a method from being overridden.

  • const NAME = value; inside a class defines a class constant.
  • Access with ClassName::CONSTANT or self::CONSTANT.
  • final class prevents extension; final public function prevents override.
Example
<?php
class HttpStatus
{
    // Class constants — typed since PHP 8.3
    const int OK                    = 200;
    const int CREATED               = 201;
    const int NO_CONTENT            = 204;
    const int BAD_REQUEST           = 400;
    const int UNAUTHORIZED          = 401;
    const int FORBIDDEN             = 403;
    const int NOT_FOUND             = 404;
    const int INTERNAL_SERVER_ERROR = 500;

    private static array $messages = [
        self::OK                    => 'OK',
        self::CREATED               => 'Created',
        self::NOT_FOUND             => 'Not Found',
        self::INTERNAL_SERVER_ERROR => 'Internal Server Error',
    ];

    public static function message(int $code): string
    {
        return self::$messages[$code] ?? 'Unknown';
    }
}

echo HttpStatus::NOT_FOUND;                  // 404
echo HttpStatus::message(HttpStatus::OK);    // OK

// final class — cannot be extended
final class Uuid
{
    private function __construct(private readonly string $value) {}

    public static function generate(): self
    {
        return new self(sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        ));
    }

    public function __toString(): string { return $this->value; }
}

$id = Uuid::generate();
echo $id; // e.g. a3f2b1c4-9d8e-4f7a-b2c1-0d3e4f5a6b7c
// class extends Uuid {} // Fatal error: Cannot extend final class
Pro Tip

Tip: PHP 8.1 introduced enums, which are ideal for named constant sets like HTTP status codes or user roles. Consider using enum HttpStatus: int { case OK = 200; case NotFound = 404; } instead of class constants for these use-cases.