0
0
PHPprogramming~5 mins

Interface constants in PHP

Choose your learning style9 modes available
Introduction

Interface constants let you store fixed values inside an interface. These values stay the same everywhere and help keep your code clear and organized.

When you want to define fixed values that all classes using the interface should share.
When you need to avoid repeating the same value in many places in your code.
When you want to give a name to a value that will not change, like a status code or a limit.
When you want to make your code easier to read by using meaningful names instead of numbers or strings.
Syntax
PHP
interface InterfaceName {
    const CONSTANT_NAME = value;
}

Constants in interfaces are always public and cannot be changed.

You access them using InterfaceName::CONSTANT_NAME.

Examples
This interface defines two constants for success and failure status codes.
PHP
interface Status {
    const SUCCESS = 1;
    const FAILURE = 0;
}
This interface sets a constant for the maximum number of users allowed.
PHP
interface Config {
    const MAX_USERS = 100;
}
Sample Program

This program defines an interface with a constant for the number of wheels. The Car class uses this constant and prints it.

PHP
<?php
interface Vehicle {
    const WHEELS = 4;
}

class Car implements Vehicle {
    public function showWheels() {
        return Vehicle::WHEELS;
    }
}

$myCar = new Car();
echo "A car has " . $myCar->showWheels() . " wheels.";
OutputSuccess
Important Notes

You cannot change interface constants once set.

Classes that implement the interface can use these constants but cannot override them.

Summary

Interface constants hold fixed values shared by all implementing classes.

They help avoid repeating magic numbers or strings in code.

Access them using InterfaceName::CONSTANT_NAME.