Advertisement

Google Ad Slot: content-top

PHP OOP - Class Constants


PHP - Class Constants


Class constants in PHP are fixed values that cannot be changed once they are defined.


Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.


Key Features of Class Constants:

  • Declared using const inside a class.
  • Cannot be changed after declaration.
  • Do not use the $ symbol.
  • Accessed using ClassName::CONSTANT_NAME.
  • Can be inherited but cannot be overridden.


Syntax


class ClassName {
  const CONSTANT_NAME = value;
}


Defining and Accessing Class Constants

Example
<?php
class Car {
const WHEELS = 4; // Defining a constant
}
// Accessing the constant using the class name
echo "A car has " . Car::WHEELS . " wheels.<br>";
?>
Try it yourself

Or, we can access a constant from inside the class by using the self keyword followed by the scope resolution operator (::) followed by the constant name, like here:

Example
<?php
class Car {
const WHEELS = 4; // Defining a constant
public function getWheels() {
return "This car has " . self::WHEELS . " wheels.";
}
}
// Accessing the constant using the class name
echo "A car has " . Car::WHEELS . " wheels.<br>";
// Accessing the constant using `self::` inside the class
$myCar = new Car();
echo $myCar->getWheels();
?>
Try it yourself