其他问题 - Trait与单例

优质
小牛编辑
136浏览
2023-12-01
  1. trait A{
  2. private static $instance;
  3. static function getInstance()
  4. {
  5. if(!isset(self::$instance)){
  6. self::$instance = new static();
  7. }
  8. return self::$instance;
  9. }
  10. }
  11. class B{
  12. use A;
  13. function a()
  14. {
  15. var_dump('call at B');
  16. }
  17. }
  18. class C extends B{
  19. function a()
  20. {
  21. var_dump('call at c');
  22. parent::a(); // TODO: Change the autogenerated stub
  23. }
  24. }
  25. class D extends B{
  26. use A;
  27. function a()
  28. {
  29. var_dump('call at D');
  30. parent::a(); // TODO: Change the autogenerated stub
  31. }
  32. }
  33. $b = B::getInstance();
  34. $c = C::getInstance();
  35. $d = D::getInstance();
  36. $c->a();
  37. $d->a();

以上输出:

  1. string(10) "B was call"
  2. string(10) "D was call"
  3. string(9) "call at B"
  4. string(9) "call at D"
  5. string(9) "call at B"