Section 3.7. Class Constants

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 by "Blue". It demonstrates the ability of accessing the constant both from inside a class method with the self keyword and via the class name "MyColorEnumClass".

As their name implies, constants are constant and can be neither changed nor removed after they are defined. Common uses for constants are defining enumerations such as in the previous example or some configuration value such as the database username, which you wouldn't want the application to be able to change.


As with global constants, you should write constant names in uppercase letters, because this is a common practice.

    PHP 5 Power Programming
    PHP 5 Power Programming
    ISBN: 013147149X
    EAN: 2147483647
    Year: 2003
    Pages: 240

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: