顾名思义,匿名类是没有名称的类。它只供一次使用,如果需要动态定义一个类。从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"
上一个:仓鼠宠物医院太原(太原仓鼠吧)
下一个:鹤壁卖狗(鹤壁新区狗市)