Blogger Information
Blog 22
fans 1
comment 1
visits 22220
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP基础-匿名类与类型约束
Miss灬懒虫
Original
911 people have browsed it

PHP基础-匿名类与类型约束

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Air15_2019
  5. * Date: 2020/2/10
  6. * Time: 19:00
  7. */
  8. /*
  9. * 匿名类和类型约束
  10. * 匿名类的使用,需要PHP7.0+ 才支持
  11. * */
  12. //一般的类
  13. class constraint{
  14. protected $a;
  15. protected $b;
  16. public function __construct($a,$b){
  17. $this->a=$a;
  18. $this->b=$b;
  19. }
  20. public function Sums() {
  21. return $this->a+$this->b;
  22. }
  23. }
  24. $a=20;
  25. $b=30;
  26. $obj_c=new constraint($a,$b);
  27. echo $obj_c->Sums();
  28. echo '<hr>';
  29. /*
  30. * 有些类,在代码中只被应用了一次,所以我们可以采用匿名类的方式,简化代码;
  31. * 匿名类,将参数放在class关键字后面,同时为了保证与实例化对象等同,所以在类名的前面使用了new 关键字,而且为了便于理解,整个类外面又被()包裹;
  32. * 被包裹的整体,就与实例化后的类的对象等同;
  33. * */
  34. echo (new class (5.5,3.2){
  35. protected $a;
  36. protected $b;
  37. public function __construct($a,$b){
  38. $this->a=$a;
  39. $this->b=$b;
  40. }
  41. public function Sums() {
  42. return $this->a+$this->b;
  43. }
  44. })->Sums();
  45. echo '<hr>';
  46. /*
  47. * 类型约束,主要是针对函数以及方法中的参数与返回值;
  48. * 添加类型约束后,参数或者返回值会按照格式进行转化和输出;
  49. * 支持约束的类型 数组/对象/类/闭包/回调/整形/布尔类型/浮点型/字符串/接口等
  50. * 这里我们用函数作为例子,因为方法本质上也是函数,所以就不再列举了;
  51. * */
  52. function total(float $price,int $number):float {
  53. return $price*$number;
  54. }
  55. echo total(6.8,6)
  56. ?>
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