PHP双冒号::的用法

双冒号操作符即作用域限定操作符Scope Resolution Operator可以访问静态、const和类中重写的属性与方法。
在类定义外使用的话,使用类名调用。在PHP 5.3.0,可以使用变量代替类名。

Program List:用变量在类定义外部访问

view source
print ?
01       
02 <?php
03 class Fruit {
04     const CONST_VALUE = 'Fruit Color';
05 }
06   
07 $classname = 'Fruit';
08 echo $classname::CONST_VALUE; // As of PHP 5.3.0
09   
10 echo Fruit::CONST_VALUE;
11 ?>

Program List:在类定义外部使用::

view source
print ?
01     
02 <?php
03 class Fruit {
04     const CONST_VALUE = 'Fruit Color';
05 }
06   
07 class Apple extends Fruit
08 {
09     public static $color = 'Red';
10   
11     public static function doubleColon() {
12         echo parent::CONST_VALUE . "\n";
13         echo self::$color . "\n";
14     }
15 }
16   
17 Apple::doubleColon();
18 ?>
程序运行结果:
view source
print ?
1 Fruit Color Red

Program List:调用parent方法

view source
print ?
01     
02 <?php
03 class Fruit
04 {
05     protected function showColor() {
06         echo "Fruit::showColor()\n";
07     }
08 }
09   
10 class Apple extends Fruit
11 {
12     // Override parent's definition
13     public function showColor()
14     {
15         // But still call the parent function
16         parent::showColor();
17         echo "Apple::showColor()\n";
18     }
19 }
20   
21 $apple = new Apple();
22 $apple->showColor();
23 ?>
程序运行结果:
view source
print ?
1 Fruit::showColor() 
2 Apple::showColor()

Program List:使用作用域限定符

view source
print ?
01     
02 <?php
03     class Apple
04     {
05         public function showColor()
06         {
07             return $this->color;
08         }
09     }
10   
11     class Banana
12     {
13         public $color;
14   
15         public function __construct()
16         {
17             $this->color = "Banana is yellow";
18         }
19   
20         public function GetColor()
21         {
22             return Apple::showColor();
23         }
24     }
25   
26     $banana = new Banana;
27     echo $banana->GetColor();
28 ?>
程序运行结果:
view source
print ?
1 Banana is yellow

Program List:调用基类的方法

view source
print ?
01       
02 <?php
03   
04 class Fruit
05 {
06     static function color()
07     {
08         return "color";
09     }
10   
11     static function showColor()
12     {
13         echo "show " . self::color();
14     }
15 }
16   
17 class Apple extends Fruit
18 {
19     static function color()
20     {
21         return "red";
22     }
23 }
24   
25 Apple::showColor();
26 // output is "show color"!
27   
28 ?>
程序运行结果:
view source
print ?
1 show color

你可能感兴趣的:(PHP,用法,休闲,双冒号,::)