如何在PHP7中使用匿名类

今天就跟大家聊聊有关如何在PHP7中使用匿名类,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

匿名类跟匿名函数一样,创建一次性的简单对象

';
echo'
'; classcommon{ public$default=10; function__construct($key){ $this->getVal($key); } publicfunctiongetVal(int$i):int{ $this->default+=$i; return$this->default+0.1; } } echo'有名函数';echo'
'; $com=newcommon(1); echo$com->getVal(2.2).'--'; echo$com->getVal(2.2).'--'; echo(newcommon(1))->getVal(8.9); echo'
';echo'匿名类'; //定义匿名类需继承 echo(newclass(1)extendscommon{})->getVal(90);echo'
'; echo(newclass(2)extendscommon{})->getVal(90);

运行效果图如下:

匿名类被嵌套进普通 Class 后,不能访问这个外部类(Outer class)的 private(私有)、protected(受保护)方法或者属性。 为了访问外部类(Outer class)protected 属性或方法,匿名类可以 extend(扩展)此外部类。 为了使用外部类(Outer class)的 private属性,必须通过构造器传进来:

prop)extendsOuter{
private$prop3;
publicfunction__construct($prop)
{
$this->prop3=$prop;
}
publicfunctionfunc3()
{
return$this->prop2+$this->prop3+$this->func1();
}
};
}
}
echo(newOuter)->func2()->func3();//6

匿名函数可以实现闭包,那么相应的匿名类也可以实现闭包

index=$i;
echo'create
'; } publicfunctiongetVal(){ echo$this->index; } }; } $arr[2]->getVal(); echo'
'; var_dump($arr[1]);

运行效果图如下:

看完上述内容,你们对如何在PHP7中使用匿名类有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注恰卡编程网行业资讯频道,感谢大家的支持。

发布于 2021-04-03 22:31:16
分享
海报
179
上一篇:如何在Laravel中使用日志 下一篇:怎么在Yii2中实现关联查询
目录

    推荐阅读

    忘记密码?

    图形验证码