PHP OOP Class Constants

🧊 PHP OOP – Class Constants

A class constant is a value inside a class that never changes.

You define it using the keyword:



 


🔷 1. Basic Class Constant Example


 

✔ Output:

Hello World

Note: You access constants using :: (Scope Resolution Operator)
No need to create an object.


🔥 2. Constants Inside Object

Even if constants belong to class, you can access using object:


 

But preferred is:



 


🟩 3. Multiple Constants in a Class


 


🟦 4. Constants Are Always Public

Class constants:

✔ Cannot be private
✔ Cannot be protected
✔ Visibility modifiers are NOT allowed

This is valid in PHP 7.1+:



 

But older PHP versions only allow:





 


🟥 5. Constants vs Variables

Feature Constant Property (Variable)
Defined using const public $name
Change value ❌ No ✔ Yes
Access using ClassName::CONST $obj->property
Memory Fixed Depends
Object required ❌ No ✔ Yes

🟧 6. Constants with Inheritance

A child class can access parent constants.


 

 


🟨 7. Overriding Constants

A child class can redefine (override) constants.


 


🟪 8. Use Class Name Dynamically


 


🟫 9. Practical Use Case of Class Constants

Example: Application configuration


 

Example: Product Types



 


🎯 Summary (Easy to Remember)

Feature Meaning
const Create constant inside class
Access ClassName::CONST_NAME
No object needed
Cannot change value
Used for fixed data

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *