PHP7匿名类的用法示例

这篇文章主要介绍了PHP7匿名类的用法,结合实例形式分析了php7匿名类、匿名函数简单定义与使用技巧,需要的朋友可以参考下。

本文实例讲述了PHP7匿名类的用法,分享给大家供大家参考,具体如下:

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Itboot
  5. * Date: 2019/1/17
  6. * Time: 18:15
  7. */
  8. class An
  9. {
  10. private $num;
  11. protected $age = 15;
  12. public function __construct() {
  13. $this->num = 1;
  14. }
  15. protected function bar(): int {
  16. return 10;
  17. }
  18. public function drive() {
  19. return new class($this->num) extends An{
  20. protected $id;
  21. public function __construct($num) {
  22. $this->id = $num;
  23. }
  24. public function ea() {
  25. return $this->id + $this->age + $this->bar();
  26. }
  27. };
  28. }
  29. }
  30. echo (new An())->drive()->ea();
  31. <?php
  32. $fun = function (){
  33. print '这是匿名函数'. PHP_EOL;
  34. };
  35. $fun();
  36. class Animal
  37. {
  38. public $num;
  39. public function __construct(...$args)
  40. {
  41. $this->num = $args[0];
  42. }
  43. public function getValue($su): int
  44. {
  45. return $this->num + $su;
  46. }
  47. }
  48. $an = new Animal(4);
  49. echo $an->getValue(12) . PHP_EOL;
  50. echo '匿名类'. PHP_EOL;
  51. echo (new class(11) extends Animal{})->getValue(12);