Constants in Classes
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 16 of 91.
Sometimes you need values in a class that should never change. Class constants provide a way to define fixed values that remain the same across all instances and cannot be modified after declaration.
You define a constant using the const keyword inside a class. By convention, constant names are written in uppercase:
<?php
class Circle {
const PI = 3.14159;
public $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return self::PI * $this->radius * $this->radius;
}
}
$circle = new Circle(5);
echo $circle->area();
Output:
78.53975Like static properties, constants belong to the class rather than individual objects. You access them using self::CONSTANT_NAME inside the class or ClassName::CONSTANT_NAME from outside:
<?php
class HttpStatus {
const OK = 200;
const NOT_FOUND = 404;
const SERVER_ERROR = 500;
}
echo HttpStatus::OK . "\n";
echo HttpStatus::NOT_FOUND;
Output:
200
404Key Point: Unlike static properties, constants cannot be changed once defined. They're ideal for values that should remain fixed throughout your application, such as configuration values, status codes, or mathematical constants.
Challenge
EasyLet's build a temperature conversion utility that uses class constants to store fixed conversion values that never change.
You'll create two files to organize your code:
Temperature.php— Define aTemperatureclass that handles temperature conversions. The class should have three constants:FREEZING_POINT_Cset to0,BOILING_POINT_Cset to100, andCONVERSION_FACTORset to1.8(used for Celsius to Fahrenheit conversion). Include apublic $celsiusproperty and a constructor that accepts and sets the Celsius value. Add atoFahrenheit()method that converts the stored Celsius temperature to Fahrenheit using the formula:(celsius * CONVERSION_FACTOR) + 32. Also add agetStatus()method that returns"Freezing"if the temperature equals the freezing point constant,"Boiling"if it equals the boiling point constant, or"Normal"otherwise.main.php— Include the Temperature class file. Create three Temperature objects with values0,100, and25. For each temperature, print the Fahrenheit conversion followed by the status on the same line in this format:"[fahrenheit]F - [status]". Each temperature should be on its own line. After printing all three, access theBOILING_POINT_Cconstant directly from the class (usingTemperature::BOILING_POINT_C) and print it on a new line.
Remember that constants are accessed using self::CONSTANT_NAME inside the class and ClassName::CONSTANT_NAME from outside. Unlike properties, constants don't use the $ symbol when accessing them.
Cheat sheet
Class constants are fixed values that never change and are shared across all instances of a class. Define them using the const keyword:
<?php
class Circle {
const PI = 3.14159;
public function area($radius) {
return self::PI * $radius * $radius;
}
}
Access constants using self::CONSTANT_NAME inside the class:
return self::PI * $radius * $radius;
Access constants using ClassName::CONSTANT_NAME from outside the class:
echo Circle::PI;
Key differences from static properties:
- Constants cannot be changed after declaration
- Constants don't use the
$symbol - Constants are ideal for fixed values like configuration settings, status codes, or mathematical constants
By convention, constant names are written in uppercase:
<?php
class HttpStatus {
const OK = 200;
const NOT_FOUND = 404;
const SERVER_ERROR = 500;
}
echo HttpStatus::OK; // 200
Try it yourself
<?php
require_once 'Temperature.php';
// TODO: Create three Temperature objects with values 0, 100, and 25
// TODO: For each temperature, print in format: "[fahrenheit]F - [status]"
// Each temperature on its own line
// TODO: Access and print BOILING_POINT_C constant directly from the class
// Use ClassName::CONSTANT_NAME syntax
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern