PHP匿名类

2023年11月27日07:55:43

介绍

顾名思义,匿名类是没有名称的类。它只供一次使用,如果需要动态定义一个类。从PHP 7版本开始引入了匿名类的功能。

匿名类的定义位于表达式内,其结果是该类的对象。它使用 新的类语法定义如下

语法

<?php
$obj=new class {
   public function sayhello(){
      echo "Hello World";
   }
};
$obj->sayhello();
?>

匿名类可以执行普通人员可以执行的所有操作,即扩展另一个类,实现接口或使用特征

在以下代码中,匿名类扩展了父类并实现了parentinterface

示例

<?php
class parentclass{
   public function test1(){
      echo "test1 method in parent class\n";
   }
}
interface parentinterface{
   public function test2();
}
$obj=new class() extends parentclass implements parentinterface {
   public function test2(){
      echo "implements test2 method from interface";
   }
};
$obj->test1();
$obj->test2();
?>

输出结果

输出如下-

test1 method in parent class
implements test2 method from interface

嵌套匿名类

匿名类可以嵌套在其他类方法的主体内。但是,其对象无权访问外部类的私有或受保护成员

示例

<?php
class testclass{
   public function test1(){
      return new class(){
         public function test2(){
            echo "test2 method of nested anonymous class";
         }
      };
   }
}
$obj2=new testclass();
$obj2->test1()->test2();
?>

输出结果

上面的代码产生以下结果-

test2 method of nested anonymous class

匿名类的内部名称

PHP解析器确实为匿名类提供了唯一的名称以供内部使用

示例

<?php
var_dump(get_class(new class() {} ));
?>

输出结果

这将产生类似于以下内容的输出-

string(60) "class@anonymous/home/cg/root/1569997/main.php0x7f1ba68da026"

  • 更新时间:2023年11月27日07:55:43 ,共 1185 字。