PHP class constants are defined inside the class using const
keywords.
Followings are the important points regarding class constant.
Source Code
<?php
class Fruits{
//create constant variable
const transportCharge= 10000;
public function calculateTotalCost(){
echo"Total cost : ".self::transportCharge;
}
}
$obj = new Fruits;
$obj->calculateTotalCost();
?>
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.
Source Code
<?php
class Trial{
//create constant variable
const a= 10;
}
//call constant variable.
echo Trial::a;
?>
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;
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;
?>