PHP Class Constants

PHP class constants are defined inside the class using const keywords.

Followings are the important points regarding class constant.

  • PHP constant value can not be changed once it is defined.
  • PHP class constant does not contain $ sign before the constant name while class property contains $ sign before its name. For example const PRODUCTION_CHARGE, public $productionCost;
  • Class constants are case-sensitive. It is recommended to name the class constants in all uppercase letters and with an underscore(_).For example const COST, const PRODUCTION_CHARGE
  • PHP constant does not have a visibility modifier.

Source Code

          <?php  
class Fruits{ 

//create constant variable 

const transportCharge= 10000;

public function calculateTotalCost(){
  echo"Total cost : ".self::transportCharge;
  }  
} 
$obj = new Fruits;
$obj->calculateTotalCost();
?>
        
Try it now

If you are inside the class then values of the constants can be get using the self keyword, but accessing the value outside the class you have to use Scope Resolution Operator.

PHP OOP Constant Access

Source Code

          <?php  
class Trial{  
 //create constant variable  
  const a= 10;  
}  
//call constant variable.  
echo Trial::a;  
?>
        
Try it now

How To Access Class Constants

There are two ways to access class constants.

Inside the class: The self keyword and scope resolution Operator (::) is used to access class constants inside the class methods. Let us see it with the help of an example.

    
   public function greet() {
   echo self::GREET;
  }
   

Outside the class: The class name and constant name are used to access a class constant from outside a class using scope resolution operator ::.

    
      echo Welcome::GREET;
   

Example

Source Code

          <?php
class User {
	const MSG = 'Learn PHP OOP Concept.';
	public function displayMessage() {
		echo self::MSG;
	}
}
$obj = new User();
$obj -> displayMessage();
echo "<br>";
echo User::MSG;
?>
        
Try it now

Web Tutorials

PHP Class Constants
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4