Blogger Information
Blog 26
fans 0
comment 0
visits 15787
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类的声明,实例化,静态成员,扩展;trait的用处和重名的解决方案
庄周梦蝶
Original
585 people have browsed it
  1. <?php
  2. //类声明,类的实例化
  3. class Introduce
  4. {
  5. protected $name;
  6. protected $age;
  7. public function __construct($name,$age)
  8. {
  9. $this->name=$name;
  10. $this->age=$age;
  11. }
  12. public function m1():string
  13. {
  14. return "我叫$this->name ,我今年$this->age 岁";
  15. }
  16. }
  17. $introduce=new Introduce('小红',20);
  18. echo $introduce->m1(),'<br>';
  19. //类的静态成员与类的扩展
  20. class Introduce1 extends Introduce
  21. {
  22. protected static $gender;
  23. public function __construct($name,$age,$gender)
  24. {
  25. parent::__construct($name,$age);
  26. self::$gender=$gender;
  27. }
  28. public function m2()
  29. {
  30. return parent::m1().",性别是:".self::$gender;
  31. }
  32. }
  33. $introduce1=new Introduce1('小红',20,'女');
  34. echo $introduce1->m2();

  1. <?php
  2. <?php
  3. //trait的功能
  4. trait A1
  5. {
  6. public function m1($a,$b)
  7. {
  8. return $a*$b;
  9. }
  10. }
  11. class B1
  12. {
  13. use A1;
  14. }
  15. class B2
  16. {
  17. use A1;
  18. }
  19. echo (new B1)->m1(6,2),'<br>';
  20. // trait与父类的区别与联系
  21. class C
  22. {
  23. public $name;
  24. public $age;
  25. public function __construct($name,$age)
  26. {
  27. $this->name=$name;
  28. $this->age=$age;
  29. }
  30. public function m1()
  31. {
  32. return "我叫 $this->name , 今年 $this->age 岁了";
  33. }
  34. }
  35. trait B
  36. {
  37. public function m2($a,$b)
  38. {
  39. return $a*$b;
  40. }
  41. }
  42. class D extends C
  43. {
  44. use B;
  45. }
  46. $d=new D('小马',20);
  47. //trait里面有类的方法,但是没有类的实例,不能实例化,只能存储一些轻量级的类方法
  48. echo $d->m1(),'<br>';
  49. echo '2X2='.$d->m2(2,2);

  1. <?php
  2. <?php
  3. //解决trait的冲突,1,设置优先级,2.给另一个起个其他的名字
  4. trait T1
  5. {
  6. public function m1($a,$b)
  7. {
  8. return $a*$b;
  9. }
  10. }
  11. trait T2
  12. {
  13. public function m1($a,$b)
  14. {
  15. return $a+$b;
  16. }
  17. }
  18. class B
  19. {
  20. use T1, T2{
  21. //1.设计优先级
  22. T1::m1 insteadOf T2;
  23. // 2.别名
  24. T2::m1 as T2m1;
  25. }
  26. }
  27. echo (new B)->m1(5,2),'<br>';
  28. echo (new B)->T2m1(2,2),'<br>';

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:重制代码看一眼,<?php重复了
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