博客列表 >php基础知识:接口类(interface)和trait

php基础知识:接口类(interface)和trait

李东亚¹⁸⁰³⁹⁵⁴⁰¹²⁰
李东亚¹⁸⁰³⁹⁵⁴⁰¹²⁰原创
2020年05月05日 17:33:021014浏览

代码练习

1、代码

  1. <?php
  2. interface iComputer
  3. {
  4. function computer();
  5. }
  6. abstract class aComputer implements iComputer
  7. {
  8. public function write(){
  9. return '<br>计算完成';
  10. }
  11. }
  12. class Computer extends aComputer
  13. {
  14. public $a;
  15. public $b;
  16. public $str;
  17. // 变量类型转换:intval()、floatval()、strval()
  18. // 变量类型强制转换(改变变量本身):intval()、floatval()、strval()
  19. public function __construct($a,$b,$c)
  20. {
  21. $this->a=$a;
  22. $this->b=$b;
  23. $this->str=$c;
  24. }
  25. function computer()
  26. {
  27. switch($this->str){
  28. case '+':
  29. // 连接.运算符和+运算符同级,所以+运算需要括起来
  30. return "{$this->a}+{$this->b}等于".($this->a+$this->b);
  31. break;
  32. case '*':
  33. return "{$this->a}*{$this->b}等于".$this->a*$this->b;
  34. break;
  35. case '/':
  36. return "{$this->a}➗{$this->b}等于".$this->a/$this->b;
  37. break;
  38. case '-':
  39. //连接.运算符和-运算符同级,所以-运算需要括起来
  40. return "{$this->a}-{$this->b}等于".($this->a-$this->b);
  41. break;
  42. default:
  43. return "{$this->a}和{$this->b}".'无法进行合法运算';
  44. }
  45. }
  46. }
  47. $sum=new Computer(20,23,'+');
  48. // echo $sum->b;
  49. echo $sum->computer();
  50. echo $sum->write();
  51. echo 'hr';
  52. echo '<br>';
  53. trait demo
  54. {
  55. function write($a){
  56. printf('trait中的方法:<pre>%s</pre>',print_r($a,true));
  57. }
  58. }
  59. class A
  60. {
  61. function write($a){
  62. printf('A类中的方法:<pre>%s</pre>',print_r($a,true));
  63. }
  64. }
  65. class B extends A
  66. {
  67. use demo;
  68. function write($a){
  69. printf('B类中的方法:<pre>%s</pre>',print_r($a,true));
  70. }
  71. }
  72. class C extends A
  73. {
  74. use demo;
  75. }
  76. class D extends A
  77. {
  78. // use demo;
  79. }
  80. (new B())->write([1,2,3,4]);
  81. (new C())->write([1,2,3,4]);
  82. (new D())->write([1,2,3,4]);

2、运行结果

总结;

1、interface接口类成员有:常量和抽象方法
2、接口类允许被多继承;implements继承关键字;
3、接口类允许被抽象类继承;
4、接口类继承中多态的应用:接口类->继承类->工作类(面向用户通用类)
5、trait类和抽象类以及接口类一样不能被实现,只能嵌入宿主中实现,trait是一个特殊类但不能用类常量;
6、如果父类和子类以及trait中有一个同名方法,优先级:子类>trait>父类;

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议