当前位置:首页 > PHP教程 > php应用 > 列表

双冒号 ::在PHP中的使用情况

发布:smiling 来源: PHP粉丝网  添加日期:2021-06-25 11:21:55 浏览: 评论:0 

前几天在百度知道里面看到有人问PHP中双冒号::的用法,当时给他的回答比较简洁因为手机打字不大方便!今天突然想起来,所以在这里总结一下我遇到的双冒号::在PHP中使用的情况。

前几天在百度知道里面看到有人问PHP中双冒号::的用法,当时给他的回答比较简洁因为手机打字不大方便!今天突然想起来,所以在这里总结一下我遇到的双冒号::在PHP中使用的情况!

双冒号操作符即作用域限定操作符Scope Resolution Operator可以访问静态、const和类中重写的属性与方法。

在类定义外使用的话,使用类名调用,在PHP 5.3.0,可以使用变量代替类名。

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

  1. <?php 
  2. class Fruit { 
  3.  const CONST_VALUE = 'Fruit Color'; 
  4. } 
  5. $classname = 'Fruit'; 
  6. echo $classname::CONST_VALUE; // As of PHP .. 
  7. echo Fruit::CONST_VALUE; 
  8. ?> 

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

  1. <?php 
  2. class Fruit { 
  3.  const CONST_VALUE = 'Fruit Color'; 
  4. } 
  5. class Apple extends Fruit 
  6. { 
  7.  public static $color = 'Red'; 
  8.  public static function doubleColon() { 
  9.   echo parent::CONST_VALUE . "\n"; 
  10.   echo self::$color . "\n"; 
  11.  } 
  12. } 
  13. Apple::doubleColon(); 
  14. ?> 

程序运行结果:

Fruit Color Red

Program List:调用parent方法

  1. <?php 
  2. class Fruit 
  3. { 
  4.  protected function showColor() { 
  5.   echo "Fruit::showColor()\n"; 
  6.  } 
  7. } 
  8. class Apple extends Fruit 
  9. { 
  10.  // Override parent's definition 
  11.  public function showColor() 
  12.  { 
  13.   // But still call the parent function 
  14.   parent::showColor(); 
  15.   echo "Apple::showColor()\n"; 
  16.  } 
  17. } 
  18. $apple = new Apple(); 
  19. $apple->showColor(); 
  20. ?> 

程序运行结果:

Fruit::showColor()

Apple::showColor()

Program List:使用作用域限定符

  1. <?php 
  2.  class Apple 
  3.  { 
  4.   public function showColor() 
  5.   { 
  6.    return $this->color; 
  7.   } 
  8.  } 
  9.  class Banana 
  10.  { 
  11.   public $color; 
  12.   public function __construct() 
  13.   { 
  14.    $this->color = "Banana is yellow"; 
  15.   } 
  16.   public function GetColor() 
  17.   { 
  18.    return Apple::showColor(); 
  19.   } 
  20.  } 
  21.  $banana = new Banana; 
  22.  echo $banana->GetColor(); 
  23. ?> 

程序运行结果:

Banana is yellow

Program List:调用基类的方法

  1. <?php 
  2. class Fruit 
  3. { 
  4.  static function color() 
  5.  { 
  6.   return "color"; 
  7.  } 
  8.  static function showColor() 
  9.  { 
  10.   echo "show " . self::color(); 
  11.  } 
  12. } 
  13. class Apple extends Fruit 
  14. { 
  15.  static function color() 
  16.  { 
  17.   return "red"; 
  18.  } 
  19. } 
  20. Apple::showColor(); 
  21. // output is "show color"! 
  22. ?> 

程序运行结果:

show color

以上内容给大家详解了::在PHP中的使用情况,希望大家喜欢。

Tags: 双冒号::

分享到: