PHP5 Tutorial – Defining Class Constants
In PHP4 the only constants that we would declare were global constants. In PHP5 it is possible to define a class level constant. These constants are specific to the class and hence don’t clutter the global level constant space.
To declare a constant in a class, PHP5 provides developers with a new keyword i.e. const; look at the example below:
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
const TYPES = “Anything”;
public function showConstant() {
echo “Echo from showConstant() : ” . Customer::TYPES;
}
}
$c = new Customer();
$c->showConstant();
Output:
Echo from showConstant() : Anything
Few important points 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 access specifiers assigned to it (private, public & protected)
Follow @phpzag

Excellent article! We will be linking to this
great content on our site. Keep up the good writing.