php中双冒号的用法是什么
本文操作环境:Windows10系统、PHP7.1版、Dell G3电脑。
双冒号操作符:即作用域限定操作符Scope Resolution Operator可以访问静态、const和类中重写的属性与方法。
1.用变量访问静态成员
其实就是用变量把类表示出来,再用双冒号再类外部访问其中的静态成员。
<?php class Fruit{ const CONST_VALUE='fruit color'; } $classname='Fruit'; echo $classname::CONST_VALUE;//fruit color ?>
访问自己的时候就把类名换成$SELF,例如:
<?php class Fruit { const CONST_VALUE = 'Fruit Color'; } class Apple extends Fruit { public static $color = 'Red'; public static function doubleColon() { echo parent::CONST_VALUE . "\n"; echo self::$color . "\n"; } } Apple::doubleColon();//Fruit Color Red ?>
2.用parent访问
访问父类的方法。
<?php class Fruit { protected function showColor() { echo "Fruit::showColor()\n"; } } class Apple extends Fruit { // Override parent's definition public function showColor() { // But still call the parent function parent::showColor(); echo "Apple::showColor()\n"; } } $apple = new Apple(); $apple->showColor(); ?>
运行结果:
Fruit::showColor()
Apple::showColor()
版权声明:
作者:后浪云
链接:https://www.idc.net/help/9395/
文章版权归作者所有,未经允许请勿转载。
THE END