3.7. Class Constants

Global constants have existed in PHP for a long time. These could be defined using the define() function, which was described in Chapter 2, “PHP 5 Basic Language.” With improved encapsulation support in PHP 5, you can now define constants inside classes. Similar to static members, they belong to the class and not to instances of the class. Class constants are always case-sensitive. The declaration syntax is intuitive, and accessing constants is similar to accessing static members:

class MyColorEnumClass {
    const RED = "Red";
    const GREEN = "Green";
    const BLUE = "Blue";

    function printBlue()
    {
        print self::BLUE;
    }
}

print MyColorEnumClass::RED;
$obj = new MyColorEnumClass();
$obj->printBlue();

This code prints "Red" followed ...

Get PHP 5 Power Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.