In our daily development work, we often encounter programming about constants. Everyone knows that constants can be understood as quantities with constant values. After a constant is defined, it cannot be changed anywhere else in the script. A constant consists of English letters. Underscores are composed of numbers, but numbers cannot be used as the first letter of a constant. Today I will introduce to you the development of PHP constants~
First download the PHP constant usage library we need for this course: http://www.php.cn/xiazai/leiku/620
After the download is completed, find the php class file we need, unzip it to our local directory, and create a new php file!
After completion, we need to call this class in the new php file and instantiate the class:
<?php include_once "dingyi2.php";//引入类文件 $foo = 'Foo'; echo $foo::BAR, '<br />'; echo Foo::BAR, '<br />'; $obj = new Foo(); //实例化列 //输出结果 echo $obj->getConstant(), '<br />'; echo $obj->getConstantValue(), '<br />'; echo Foo::getConstantValue(); ?>
Run the file and the result will be as shown below:
So regarding the subclass inheriting the parent class, the subclass can rewrite the parent class:
<?php include_once "dingyi2.php";//引入类文件 $obj = new Bar(); //实例化列 //输出结果 echo $obj->getMyConstant(), '<br />';// foo echo $obj->getParentConstant(), '<br />';// bar ?>
Run this file, and the result will be as shown below:
Note:
1. Class constants belong to the class itself, not to object instances, and cannot be passed Object instance access
2. Cannot be modified with public, protected, private, static
3. Subclasses can override constants in the parent class and call constants in the parent class through (parent::)
4. 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 or static).
The above is the detailed content of Code idea development for php constant usage. For more information, please follow other related articles on the PHP Chinese website!