You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.8 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. <?php
  2. /*
  3. * @Author: your name
  4. * @Date: 2022-03-12 15:09:52
  5. * @LastEditTime: 2022-03-14 10:35:02
  6. * @LastEditors: Please set LastEditors
  7. * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
  8. * @FilePath: /wiggins/myDemo/php_demo/07面向对象/12-类常量.php
  9. */
  10. /**
  11. * 类里面的常量
  12. * 类常量不属于类的属性,与类属性等级并列
  13. * 类属于类本身,不属于对象,不能通过‘->'访问
  14. * 子类可以重写父类的类常量,通过区域解析符(parent::)调用父类中的类常量
  15. */
  16. class ClassA
  17. {
  18. //定义类常量
  19. const a='这是一个类常量';
  20. function func()
  21. {
  22. //在类的方法中调用本类常量
  23. echo self::a.PHP_EOL;
  24. }
  25. }
  26. //直接调用类常量
  27. echo ClassA::a.PHP_EOL;
  28. //对象::类常量,PHP5.3起可以使用变量调用类常量
  29. $obj = new ClassA();
  30. echo $obj::a.PHP_EOL;
  31. //echo $obj->a.'<br>'; //对象不能访问类常量,会报“Undefined property: ClassA::$a”
  32. //对象中方法调用类常量
  33. $obj->func();
  34. //访问父类类常量
  35. class ClassB extends ClassA
  36. {
  37. function func(){
  38. echo parent::a.PHP_EOL;
  39. }
  40. }
  41. echo "调用父类的类常量".PHP_EOL;
  42. $obj=new ClassB();
  43. $obj->func();
  44. //重写父类的类常量
  45. class ClassC extends ClassA
  46. {
  47. const a = "这个一个被子类重写的类常量";
  48. function func(){
  49. echo parent::a.PHP_EOL;
  50. }
  51. }
  52. echo ClassC::a.PHP_EOL; //被子类重写的类常量
  53. $obj=new ClassB(); //这是一个类常量
  54. $obj->func();
  55. /**
  56. * 感悟:类常量估计是在编译时已经实例化在内存的东西,所以不能再实例化
  57. */
  58. ?>