A few days ago, I saw someone asking about the usage of double colon:: in PHP. The answer I gave him was quite concise because it was not very convenient to type on your phone! I suddenly remembered it today, so here I summarize the situations I encountered with double colon:: in PHP!
The double colon operator is the scope-qualified operator. Scope Resolution Operator can access static, const and overridden properties and methods in classes.
If used outside the class definition, use the class name to call it. In PHP 5.3.0, variables can be used instead of class names.
Program List: Use variables to define external access in class
<?php class Fruit { const CONST_VALUE = 'Fruit Color'; } $classname = 'Fruit'; echo $classname::CONST_VALUE; // As of PHP .. echo Fruit::CONST_VALUE; ?> Program List:Use outside the class definition:: <?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(); ?>
Program running results:
Fruit Color Red
Program List: Call parent method
<?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(); ?>
Program running results:
Fruit::showColor()
Apple::showColor()
Program List: Use scope qualifiers
<?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 results:
Banana is yellow
Program List: Calling the base class method
<?php class 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 results:
show color
The above content gives you a detailed explanation::The usage in PHP, I hope you like it.