PHP7匿名类的用法示例

yipeiwu_com6年前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程序设计有所帮助。

相关文章

php使用curl抓取qq空间的访客信息示例

config.php 复制代码 代码如下:<?phpdefine('APP_DIR', dirname(__FILE__));define('COOKIE_FILE', APP_D...

PHP 引用是个坏习惯

复制代码 代码如下: function binsearch(&$arr, $key, $value) { $low = 0; $high = count($arr); while ($l...

php删除左端与右端空格的方法

本文实例讲述了php删除左端与右端空格的方法。分享给大家供大家参考。具体方法如下: 在php中删除函数比js要具体很多,除了trim()函数,还有ltrim()和rtrim()函数,他们...

最常用的8款PHP调试工具

Web 开发并不是一项轻松的任务,有超级多服务端脚本语言提供给开发者,但是当前 PHP 因为具有额外的一些强大的功能而越来越流行。PHP 是最强大的服务端脚本语言之一,同时也是 Web...

php创建图像具体步骤

php创建图像具体步骤

php 的图像处理在验证码是最常见的,下面说下使用php创建图像的具体步骤。 简要说明:PHP 并不仅限于创建 HTML 输出, 它也可以创建和处理包括 GIF,PNG(推荐),JPEG...