首页 > 开发 > PHP > 正文

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

2024-05-04 23:40:08
字体:大 中 小
来源:转载
供稿:网友

前几天在百度知道里面看到有人问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. ?> 
  9. Program List:在类定义外部使用:: 
  10. <?php 
  11. class Fruit { 
  12. const CONST_VALUE = 'Fruit Color'; 
  13. } 
  14. class Apple extends Fruit 
  15. { 
  16. public static $color = 'Red'; 
  17. public static function doubleColon() { 
  18. echo parent::CONST_VALUE . "/n"; 
  19. echo self::$color . "/n"; 
  20. } 
  21. } 
  22. Apple::doubleColon(); 
  23. ?> 

程序运行结果:

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中的使用情况,希望大家喜欢。


注:相关教程知识阅读请移步到PHP教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表