Learn PHP Tutorial

PHP OOP – Class Constants


PHP allows to define constant data within a class, which value remains the same and unchangeable.

The default visibility of a class constant is public. A class constant is declared inside the class with the “const” keyword.

We can access a constant value from outside the class by using the class name followed by the scope resolution operator (::) followed by the constant name.

Let us understand with an example

<?php
class Welcome {
  const WELCOME_MESSAGE= "Welcome to Share Query!";
}

echo Welcome::WELCOME_MESSAGE;
?>

We can access a constant value from inside the class by using the self keyword followed by the scope resolution operator (::) followed by the constant name.

<?php
class Welcome {
   const WELCOME_MESSAGE= "Welcome to Share Query!";
   public function welcome_msg()
   {
      echo self::WELCOME_MESSAGE;
   }
}

$obj =  new Welcome();
$obj->welcome_msg();
?>