Some properties should not be changed. The Answer to Life, the Universe, and Everything is 42, and you want it to stay that way. Error and status flags will often be hard-coded into your classes. Although they should be publicly and statically available, client code should not be able to change them. PHP allows you to define constant properties within a class. Like global constants, class constants cannot be changed once they are set. A constant property is declared with the const keyword. Constants are not prefixed with a dollar sign like regular properties. By convention, they are often named using only uppercase characters:

<?php
class ShopProduct
{    
    const AVAILABLE      = 0;
    const OUT_OF_STOCK   = 1;
}

Constant properties can contain only primitive values. You cannot assign an object to a constant. Like static properties, constant properties are accessed through the class and not an instance. Just as you define a constant without a dollar sign, no leading symbol is required when you refer to one:

<?php
print ShopProduct::AVAILABLE;

This post is part of series:

1 - Object Oriented Programming Concept2 - Classes3 - Objects4 - Methods5 - Constructors6 - Arguments and Types7 - Static Methods and Properties8 - Constant Properties9 - Abstract Classes10 - Interfaces11 - Traits
OOP#OOPPHP#PHP

Comments (0)