This article mainly introduces the usage of php classconstants. The examples analyze the concepts, characteristics and related usage skills of class constants in php. Friends in need can refer to the examples in this article
Describes the usage of PHP class constants. Share it with everyone for your reference. The details are as follows:
Class constants belong to the class itself, not toobjectinstances, and cannot be accessed through object instances
Subclasses can override constants in parent classes , you can call the constants in the parent class through (parent::)
Since PHP5.3.0, you can use a variable to dynamically call the class. But the value of this variable cannot be a keyword (such as self, parent orstatic).
Constant values can only be scalars, string, bool,integer, float, null. You can use the nowdoc structure to initialize constants
'; echo Foo::BAR, '
'; $obj = new Foo(); echo $obj->getConstant(), '
'; echo $obj->getConstantValue(), '
'; echo Foo::getConstantValue(); // 以上均输出bar class Bar extends Foo { const BAR = 'foo'; // 重写父类常量 public static function getMyConstant() { return self::BAR; } public static function getParentConstant() { return parent::BAR; } } echo Bar::getMyConstant(); // foo echo Bar::getParentConstant(); // bar
The above is the detailed content of What are php class constants? Detailed explanation of class constant usage. For more information, please follow other related articles on the PHP Chinese website!