PHP Class Constants

Defining unchangeable values in classes

💎 What are Class Constants?

Class constants are fixed values that cannot be changed once defined. They're declared using the const keyword and accessed using the class name or self:: keyword, perfect for storing configuration values.


<?php
class MathHelper {
    const PI = 3.14159;
    const E = 2.71828;
    
    public function circleArea($radius) {
        return self::PI * $radius * $radius;
    }
}

// Access constant without creating object
echo "PI value: " . MathHelper::PI;

// Use in method
$math = new MathHelper();
echo "Circle area: " . $math->circleArea(5);
?>
                                    

Output:

PI value: 3.14159

Circle area: 78.53975

Constant Features

🔒

Immutable

Cannot be changed after definition

const MAX_SIZE = 100;
// Cannot reassign
🌐

Static Access

Access without creating an object

ClassName::CONSTANT;
self::CONSTANT;
📝

Naming Convention

Use UPPERCASE with underscores

const MAX_VALUE = 100;
const DEFAULT_NAME = "User";
🎯

Visibility

Can have access modifiers (PHP 7.1+)

public const PUBLIC_VAL = 1;
private const PRIVATE_VAL = 2;

🔹 Defining Class Constants

Constants are defined using the const keyword inside a class. They must be assigned a value at declaration and cannot use variables or expressions.

<?php
class Database {
    const HOST = "localhost";
    const PORT = 3306;
    const DATABASE_NAME = "myapp";
    const CHARSET = "utf8mb4";
    
    public function getConnectionString() {
        return "mysql:host=" . self::HOST . 
               ";port=" . self::PORT . 
               ";dbname=" . self::DATABASE_NAME . 
               ";charset=" . self::CHARSET;
    }
}

echo "Host: " . Database::HOST;
echo "Port: " . Database::PORT;

$db = new Database();
echo $db->getConnectionString();
?>

Output:

Host: localhost

Port: 3306

mysql:host=localhost;port=3306;dbname=myapp;charset=utf8mb4

🔹 Accessing Constants

Constants can be accessed using the class name with :: operator from outside the class, or using self:: from inside the class.

<?php
class Status {
    const PENDING = "pending";
    const APPROVED = "approved";
    const REJECTED = "rejected";
    
    public function getStatusMessage($status) {
        if ($status === self::PENDING) {
            return "Your request is pending review.";
        } elseif ($status === self::APPROVED) {
            return "Your request has been approved!";
        } elseif ($status === self::REJECTED) {
            return "Your request was rejected.";
        }
        return "Unknown status.";
    }
}

// Access from outside class
echo "Status: " . Status::PENDING;
echo "Status: " . Status::APPROVED;

// Use in method
$statusObj = new Status();
echo $statusObj->getStatusMessage(Status::APPROVED);
echo $statusObj->getStatusMessage(Status::REJECTED);
?>

Output:

Status: pending

Status: approved

Your request has been approved!

Your request was rejected.

🔹 Constants with Access Modifiers

Since PHP 7.1, constants can have visibility modifiers (public, private, protected). This controls where the constant can be accessed from.

<?php
class Config {
    public const APP_NAME = "MyApp";
    public const VERSION = "1.0.0";
    private const SECRET_KEY = "abc123xyz";
    protected const MAX_ATTEMPTS = 3;
    
    public function getAppInfo() {
        // Can access all constants inside class
        return self::APP_NAME . " v" . self::VERSION . 
               " (Key: " . self::SECRET_KEY . ")";
    }
    
    public function validateAttempts($attempts) {
        return $attempts <= self::MAX_ATTEMPTS;
    }
}

class ExtendedConfig extends Config {
    public function getMaxAttempts() {
        // Can access protected constant in child class
        return "Max attempts: " . self::MAX_ATTEMPTS;
    }
}

// Public constants accessible
echo Config::APP_NAME;
echo Config::VERSION;

$config = new Config();
echo $config->getAppInfo();

// echo Config::SECRET_KEY;  // Error: private constant

$extended = new ExtendedConfig();
echo $extended->getMaxAttempts();
?>

Output:

MyApp

1.0.0

MyApp v1.0.0 (Key: abc123xyz)

Max attempts: 3

🔹 Constants in Inheritance

Child classes inherit parent class constants and can access them. However, constants cannot be overridden in the same way as methods.

<?php
class Vehicle {
    const TYPE = "Generic Vehicle";
    const WHEELS = 4;
    
    public function getInfo() {
        return "Type: " . self::TYPE . ", Wheels: " . self::WHEELS;
    }
}

class Motorcycle extends Vehicle {
    const TYPE = "Motorcycle";  // Define new constant
    const WHEELS = 2;
    
    public function getParentType() {
        return "Parent type: " . parent::TYPE;
    }
}

$vehicle = new Vehicle();
echo $vehicle->getInfo();

$motorcycle = new Motorcycle();
echo $motorcycle->getInfo();
echo $motorcycle->getParentType();

echo "Vehicle wheels: " . Vehicle::WHEELS;
echo "Motorcycle wheels: " . Motorcycle::WHEELS;
?>

Output:

Type: Generic Vehicle, Wheels: 4

Type: Motorcycle, Wheels: 2

Parent type: Generic Vehicle

Vehicle wheels: 4

Motorcycle wheels: 2

🔹 Practical Example: API Configuration

Class constants are perfect for storing configuration values, API endpoints, error codes, and other fixed values used throughout your application.

<?php
class ApiClient {
    const BASE_URL = "https://api.example.com";
    const VERSION = "v1";
    const TIMEOUT = 30;
    
    // HTTP Status codes
    const HTTP_OK = 200;
    const HTTP_CREATED = 201;
    const HTTP_BAD_REQUEST = 400;
    const HTTP_UNAUTHORIZED = 401;
    const HTTP_NOT_FOUND = 404;
    
    // Endpoints
    const ENDPOINT_USERS = "/users";
    const ENDPOINT_POSTS = "/posts";
    
    public function getEndpoint($resource) {
        return self::BASE_URL . "/" . self::VERSION . $resource;
    }
    
    public function getStatusMessage($code) {
        switch ($code) {
            case self::HTTP_OK:
                return "Success";
            case self::HTTP_CREATED:
                return "Resource created";
            case self::HTTP_BAD_REQUEST:
                return "Bad request";
            case self::HTTP_UNAUTHORIZED:
                return "Unauthorized";
            case self::HTTP_NOT_FOUND:
                return "Not found";
            default:
                return "Unknown status";
        }
    }
}

$api = new ApiClient();
echo "Users endpoint: " . $api->getEndpoint(ApiClient::ENDPOINT_USERS);
echo "Posts endpoint: " . $api->getEndpoint(ApiClient::ENDPOINT_POSTS);
echo "Timeout: " . ApiClient::TIMEOUT . " seconds";
echo "Status 200: " . $api->getStatusMessage(ApiClient::HTTP_OK);
echo "Status 404: " . $api->getStatusMessage(ApiClient::HTTP_NOT_FOUND);
?>

Output:

Users endpoint: https://api.example.com/v1/users

Posts endpoint: https://api.example.com/v1/posts

Timeout: 30 seconds

Status 200: Success

Status 404: Not found

🧠 Test Your Knowledge

How do you access a class constant from outside the class?