Home > Article > Backend Development > php class constants
You can define values that remain unchanged in the class as constants. There is no need to use the $ symbol when defining and using constants.
The value of a constant must be a fixed value and cannot be a variable, class attribute, the result of a mathematical operation or a function call.
Constants can also be defined in interfaces.
Since PHP 5.3.0, you can use a variable to dynamically call a class. But the variable value cannot be a keyword (such as self, parent or static).
Example #1 Define and use a class constant
class MyClass { const constant = 1; function showConstant(){ echo self::constant.'<br>'; } } echo MyClass::constant.'<br>'; $className = "MyClass"; echo $className::constant.'<br>'; //自PHP5.3.0起 $class = new MyClass(); $class -> showConstant(); echo $class::constant.'<br>';
Example #2 Static data example
class foo{ const bar = <<<'EOT' bar EOT; }
Unlike heredoc, nowdoc can be used in any static data.