PHP OOP Class Constants

PHP Tutorial

PHP OOP Class Constants

In PHP OOP Class Constants 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

FeatureConstantProperty (Variable)
Defined usingconstpublic $name
Change value No Yes
Access usingClassName::CONST$obj->property
MemoryFixedDepends
Object requiredNoYes

 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)

FeatureMeaning
constCreate constant inside class
AccessClassName::CONST_NAME
No object neededYes
Cannot change value Yes
Used for fixed data Yes

You may also like...