⇧
vadnica-logo
My Services About the Project Telegram O meni O meni

OOP Basics: Class Constants

In PHP, we use the const keyword to define constants inside classes. The main characteristic of constants is that their value cannot be changed after they are defined. Unlike regular properties, constants belong to the class itself and not to an individual object, which is why we access them using the :: operator.

EXAMPLE
RESULT
The result will be displayed here...

Example Explanation: Where Does the Output Come From?

You might be wondering: "How can Fuel or Electricity be printed if there are no variables (the ones with the $ sign) in the code at all?" The answer lies in the nature of constants. Constants are not variables, but fixed values that are literally "hardcoded" into the class itself.

Main Differences in Access

For a better visualization, take a look at the table below, which shows how different data types behave in code:

Data Type Class Syntax Access Method Output Example
Variable public $color; $object->color Red (only this car)
Constant const VOLTAGE = 230; Class::VOLTAGE 230 (for all objects)
Global define("PI", 3.14); PI 3.14 (everywhere in code)

Using Constants Inside a Class (self::)

When you want to access a constant inside a local method within the same class, you do not use $this, but the self keyword. This is because $this points to the object, whereas self points to the class.

Additional Tools for Working with Constants

PHP also offers built-in functions for creating, checking, and dynamically accessing global constants:

Function Name Description Example
define() Creates a new global constant. define("PI", 3.14);
defined() Checks whether a constant with a specific name already exists. if(defined("PI")) { ... }
constant() Returns the value of a constant (useful when the constant name is stored inside a variable). echo constant($constant_name);