PHP Class Constants

PHP Class Constants

Constants cannot be changed once they are declared. If you need to define some constant data within a class, a Class Constant is what you are looking for.

Class constants can be useful if you need to define settings, states, or warning messages that belong to a class and should remain fixed.


Defining and Accessing a Constant

A class constant is declared inside a class with the const keyword. By default, they are highly accessible.

Class constants are completely different from regular variables. We do not use the $ symbol to declare or access them, and we do not use the $this keyword or the -> operator.

Instead, we use the Scope Resolution Operator (::).

Class Constant Example

<?php
class Goodbye {
  const LEAVING_MESSAGE = "Thank you for visiting IntricateDevo!";
  

public function byebye() { // Accessing a constant from INSIDE the class uses self:: echo self::LEAVING_MESSAGE; } }

// Accessing a constant from OUTSIDE the class uses ClassName:: echo Goodbye::LEAVING_MESSAGE; echo "\n";

$obj = new Goodbye(); $obj->byebye(); ?>