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

相关文章

PHP5下$_SERVER变量不再受magic_quotes_gpc保护的弥补方法

复制代码 代码如下: <?php $magic_quotes_gpc = get_magic_quotes_gpc(); @extract(daddslashes($_COOKIE...

php中static和const关键字用法分析

php中static和const关键字用法分析

本文实例讲述了php中static和const关键字用法。分享给大家供大家参考,具体如下: static关键字在类中描述的成员属性和成员函数都是静态的。 static成员能限制外部的访问...

php实现数组纵向转横向并过滤重复值的方法分析

本文实例讲述了php实现数组纵向转横向并过滤重复值的方法。分享给大家供大家参考,具体如下: 一、问题 有数组: array( 6=>array(5=>'黑xx', 4...

PHP可变函数的使用详解

PHP 支持可变函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且尝试执行它。可变函数可以用来实现包括回调函数,函数表在内的一些用途。 变量函数不能用...

PHP 配置文件中open_basedir选项作用

如下是php.ini中的原文说明以及默认配置: ; open_basedir, if set, limits all file operations to the defined dir...