PHP7匿名类的用法示例

yipeiwu_com5年前PHP代码库

本文实例讲述了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面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

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

相关文章

drupal 代码实现URL重写

以下是实现例子: 复制代码 代码如下: /* * 伪地址转原地址 (url_alter) */ function example_url_inbound_alter(&$path, $o...

纯php生成随机密码

纯php生成随机密码

php生成一个随机的密码,方便快捷,可以随机生成安全可靠的密码。 分享代码如下 <?php header("Content-type:text/html;chars...

php中get_magic_quotes_gpc()函数说明

get_magic_quotes_gpc函数是一个用来判断是否为用户提供的数据增加斜线了,这个在php.ini配置文件中哦,下面我来介绍一下get_magic_quotes_gpc()函...

PHP闭包函数详解

匿名函数也叫闭包函数(closures允许创建一个没有指定没成的函数,最经常用作回调函数参数的值。 闭包函数没有函数名称,直接在function()传入变量即可 使用时将定义的变量当作函...

PHP获取一年中每个星期的开始和结束日期的方法

本文实例讲述了PHP获取一年中每个星期的开始和结束日期的方法。分享给大家供大家参考。具体分析如下: 最近项目中需要做个提交周报的功能,需要知道指定周数的开始日期和结束日期,以便处理其他业...