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


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.