开放的编程资料库

当前位置:我爱分享网 > PHP教程 > 正文

PHP7匿名类的用法示例

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

<?php
/**
 * Created by PhpStorm.
 * User: Itboot
 * Date: 2019/1/17
 * Time: 18:15
 */
class An
{
  private $num;
  protected $age = 15;
  public function __construct() {
    $this->num = 1;
  }
  protected function bar(): int {
    return 10;
  }
  public function drive() {
    return new class($this->num) extends An{
      protected $id;
      public function __construct($num) {
        $this->id = $num;
      }
      public function ea() {
        return $this->id + $this->age + $this->bar();
      }
    };
  }
}
echo (new An())->drive()->ea();

<?php
$fun = function (){
  print '这是匿名函数'. PHP_EOL;
};
$fun();
class Animal
{
  public $num;
  public function __construct(...$args)
  {
    $this->num = $args[0];
  }
  public function getValue($su): int
  {
    return $this->num + $su;
  }
}
$an = new Animal(4);
echo $an->getValue(12) . PHP_EOL;
echo '匿名类'. PHP_EOL;
echo (new class(11) extends Animal{})->getValue(12);

更多关于PHP相关内容感兴趣的读者可查看本站专题:《
》、《
》、《
》、《
》、《
》、《
》及《

希望本文所述对大家PHP程序设计有所帮助。


您可能感兴趣的文章:

未经允许不得转载:我爱分享网 » PHP7匿名类的用法示例

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏