Tutorial by Examples

Simple check To check if constant is defined use the defined function. Note that this function doesn't care about constant's value, it only cares if the constant exists or not. Even if the value of the constant is null or false the function will still return true. <?php define("GOOD&quo...
Constants are created using the const statement or the define function. The convention is to use UPPERCASE letters for constant names. Define constant using explicit values const PI = 3.14; // float define("EARTH_IS_FLAT", false); // boolean const "UNKNOWN" = null; // null d...
Constants can be defined inside classes using a const keyword. class Foo { const BAR_TYPE = "bar"; // reference from inside the class using self:: public function myMethod() { return self::BAR_TYPE; } } // reference from outside the class using <Class...
Arrays can be used as plain constants and class constants from version PHP 5.6 onwards: Class constant example class Answer { const C = [2,4]; } print Answer::C[1] . Answer::C[0]; // 42 Plain constant example const ANSWER = [2,4]; print ANSWER[1] . ANSWER[0]; // 42 Also from versi...
To use the constant simply use its name: if (EARTH_IS_FLAT) { print "Earth is flat"; } print APP_ENV_UPPERCASE; or if you don't know the name of the constant in advance, use the constant function: // this code is equivalent to the above code $const1 = "EARTH_IS_FLAT&quo...

Page 1 of 1