Define Class Constants in Php


In PHP4 the only constants that we would declare were global constants. In PHP5 it is possible to define a class level constants. These constants are specific to the class and hence don’t clutter the global level space.
To declare a constant in a class, PHP5 provides developers with a new keyword i.e. const; look at the example below:
class Customer {
 const TYPES = "Anything";
}
 
echo "Types are : " . Customer::TYPES;
In the above example, const is a keyword and TYPES is the name of the constant. Outside the class definition we echo the value of the constant by using the scope resolution operator (::) like this Customer::TYPES. Observe that we don’t need to create an object of the class to make use of the constant.
The next logical question is if we can create an object of the Customer class and using the scope resolution operator access the constant. The answer is no; reason – because a constant belongs to the class definition scope and not to an object.
Example of accessing Constants within a function
class Customer {
 const TYPES = "Anything";
 
 public function showConstant() {
  echo "Echo from showConstant() : " . Customer::TYPES;
 }
 
}
 
$c = new Customer();
$c->showConstant();
Output:
Echo from showConstant() : Anything
Some observations on Constants
  • Variables defined as constants cannot be changed.
  • Only a string or numeric value can be assigned to a constant.
  • Arrays, Objects & Expressions cannot be assigned to a constant.
  • A class constant can only be accessed via the scope resolution operator (::) executed on the class name.
  • A class constant cannot have <a>access specifiers</a> assigned to it (public,private & protected)