0
0
PHPprogramming~5 mins

Constants in classes in PHP

Choose your learning style9 modes available
Introduction

Constants in classes hold values that do not change. They help keep important data safe and easy to use.

When you want to store a fixed value related to a class, like a version number.
When you need a value that should be the same for all objects of a class.
When you want to avoid magic numbers or strings scattered in your code.
When you want to give a name to a value that never changes, making code clearer.
Syntax
PHP
class ClassName {
    const CONSTANT_NAME = value;
}

Constants are declared with the keyword const inside a class.

Constant names are usually uppercase by convention.

Examples
This class has a constant WHEELS set to 4.
PHP
class Car {
    const WHEELS = 4;
}
Here, PI is a constant representing the value of pi.
PHP
class Circle {
    const PI = 3.14159;
}
This class defines two string constants for user roles.
PHP
class User {
    const ROLE_ADMIN = 'admin';
    const ROLE_GUEST = 'guest';
}
Sample Program

This program defines a class Fruit with a constant COLOR. It then prints the color using the constant.

PHP
<?php
class Fruit {
    const COLOR = 'red';
}

echo "The color of the fruit is " . Fruit::COLOR . ".";
OutputSuccess
Important Notes

You access class constants using the scope resolution operator ::, like ClassName::CONSTANT_NAME.

Constants cannot be changed once set. They are different from variables.

Constants are always public and can be accessed without creating an object.

Summary

Constants store fixed values inside classes.

Use const keyword to declare them.

Access constants with ClassName::CONSTANT_NAME.