PHP can create constants within classes.

To define a class constant, use the keyword const, as follows:

class MyClass {
           const MYCONST = 123;

Like static properties, you access class constants via the class name and the :: operator:

echo MyClass::MYCONST;

Class constants are useful whenever you need to define a fixed value, or set a configuration option, that's specific to the class in question.

For example, for the Truck class you could define class constants to represent various types of Trucks, then use these constants when creating Truck objects:


         class Truck {
           const HATCHBACK = 1;
           const STATION_WAGON = 2;
           const SUV = 3;

           public $model;
           public $color;
           public $manufacturer;
           public $type;
         }//from w  w  w. java2s. c  o  m

         $myTruck = new Truck;
         $myTruck->model ="Dodge Caliber";
         $myTruck->color ="blue";
         $myTruck->manufacturer ="Chrysler";
         $myTruck->type = Truck::HATCHBACK;

         echo"This $myTruck->model is a";
         switch ($myTruck->type) {
           case Truck::HATCHBACK:
           case Truck::STATION_WAGON:
             echo"station wagon";
           case Truck::SUV:


In this example, the Truck class contains three class constants - HATCHBACK, STATION_WAGON, and SUV - that are assigned the values 1, 2, and 3, respectively.

These constants are then used when setting and reading the $type property of the $myTruck object.

Related Topic