Blogger Information
Blog 40
fans 0
comment 1
visits 39764
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
后期静态绑定案例
Dong.
Original
668 people have browsed it

1. self()创建2个类的实例(只绑定声明类方法create)

  1. <?php
  2. abstract class CreateInstance
  3. {
  4. }
  5. class User1 extends CreateInstance
  6. {
  7. // 创建类的实例
  8. public static function create() : self
  9. {
  10. return new self();
  11. }
  12. }
  13. class User2 extends CreateInstance
  14. {
  15. // 创建类的实例
  16. public static function create() : self
  17. {
  18. return new self();
  19. }
  20. }
  21. // 生成User1实例
  22. $user1 = User1::create();
  23. var_dump($user);
  24. echo "<hr>";
  25. // 生成User2实例
  26. $user2 = User2::create();
  27. var_dump($user2);

2. static 后期静态绑定

  1. <?php
  2. // static后期静态绑定
  3. abstract class CreateInstance
  4. {
  5. public static $name;
  6. public static $age;
  7. // 创建类的实例
  8. public static function show()
  9. {
  10. return '姓名:'. static::$name . ',年龄:' .static::$age;
  11. }
  12. }
  13. class User1 extends CreateInstance
  14. {
  15. public static $name='小芳';
  16. public static $age='20';
  17. }
  18. class User2 extends CreateInstance
  19. {
  20. public static $name='小李';
  21. public static $age='21';
  22. }
  23. // 生成User1实例
  24. echo User1::show();
  25. echo "<hr>";
  26. // 生成User2实例
  27. echo User2::show();

总结

  • 使用 self:: 或者 CLASS 对当前类的静态引用,取决于定义当前方法所在的类,只能绑定当前类方法,不能与调用类绑定
  • static:: 只能用于静态属性。
  • static可以绑定调用类
  • 将声明类与调用类分离,换关键词,用static,后期静态绑定,才能调用
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:在许多场景中, self 和 static几乎无区别
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post