Declaring Constants

In the same way that you can create a global constant with the define function, you can define constants inside classes. The generally accepted practice is to use uppercase letters to make them stand out.

class Translate
    const ENGLISH = 0;
    const SPANISH = 1;
    const FRENCH = 2;
    const GERMAN = 3;
    // ...
    function lookup()
        echo self::SPANISH;
		echo self::GERMAN;

Constants can be referenced directly, using the self keyword and double colon operator. Note that this code calls the class directly, using the double colon operator at line one, without creating an instance of it first. As you would expect, the value printed when you run this code is 1.
Remember that once you define a constant, you can’t change it.



You may also like...