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.
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.
const keyword and do not
have a dollar sign. This tells PHP that this value will never change.object
(your specific car), while constants belong to the class (all vehicles in the world).:: operator (e.g., Vehicle::CONSTANT_NAME).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) |
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.
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); |