A few days ago, I saw someone asking for the use of double colons: In PHP in Baidu. at that time, the answer I gave him was concise because mobile phone typing was not very convenient! Today I suddenly remembered it, so here I would like to sum up the double colon: Used in PHP. a few days ago, I saw someone asking me how to use the double colon: in PHP, at that time, his answer was concise because mobile phone typing was not convenient! Today I suddenly remembered, so here I will summarize the double colons I encountered: usage in PHP!
The dual-colon Operator is the Scope limitation Operator. Scope Resolution Operator can access static, const, and attributes and methods that are rewritten in the class.
Use the class name for calling when it is used outside the class definition. In PHP 5.3.0, you can use variables instead of class names.
Program List: use variables to define external access in the class
<? Phpclass Fruit {const CONST_VALUE = 'fruit color';} $ classname = 'fruit'; echo $ classname: CONST_VALUE; // As of PHP .. echo Fruit: CONST_VALUE;?> Program List: used outside the class definition: <? Phpclass 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 ();?>
Program running result:
Fruit Color Red
Program List: call the parent method
<?phpclass 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();?>
Program running result:
Fruit: showColor ()
Apple: showColor ()
Program List: Use the scope qualifier
<?php class Apple { public function showColor() { return $this->color; } } class Banana { public $color; public function __construct() { $this->color = "Banana is yellow"; } public function GetColor() { return Apple::showColor(); } } $banana = new Banana; echo $banana->GetColor();?>
Program running result:
Banana is yellow
Program List: call the method of the base class
<?phpclass Fruit{ static function color() { return "color"; } static function showColor() { echo "show " . self::color(); }}class Apple extends Fruit{ static function color() { return "red"; }}Apple::showColor();// output is "show color"!?>
Program running result:
Show color
The above content will be explained to you: I hope you will like the usage in PHP.