PHP7匿名类用法分析
本文实例讲述了PHP7匿名类用法。分享给大家供大家参考,具体如下:
匿名类跟匿名函数一样,创建一次性的简单对象
?php/** *由PhpStorm创建。*用户:蜜蜂*日期: 2016/4/24 *时间: 00:17 */回音'匿名函数;$ anonymous _ func=func(){ return ' func ';};echo $ anonymous _ func();回声“br”;回声' hr类common { public $ default=10 function _ _ construct($ key){ $ this-GetVal($ key);}公共函数GetVal(int $ I): int { $ this-default=$ I;返回$这个-默认值0.1;}}echo '有名函数;回声“br”;$com=新公共(1);echo $com-getVal(2.2).”- ';echo $com-getVal(2.2).”- ';回声(新公共(1))-GetVal(8.9);echo ' hr "回声"匿名类;//定义匿名类需继承回声(新类(1)扩展了common { })-getVal(90);回声“br”;回声(新类(2)扩展了common { })-getVal(90);运行效果图如下:
匿名类被嵌套进普通班级后,不能访问这个外部类(外班)的私人(私有)、受保护(受保护)方法或者属性。为了访问外部类(外层)受保护属性或方法,匿名类可以扩展(扩展)此外部类。为了使用外部类(外班)的私人的属性,必须通过构造器传进来:
?phpclass Outer { private $ prop=1;受保护的$ prop2=2受保护的函数func 1(){ return 3;} public func 2(){返回新类($ this-prop)扩展了外部{ private $ prop 3 public function _ _ construct($ prop){ $ this-prop 3=$ prop;} public func 3(){ 0返回$ this-prop 2 $ this-prop 3 $ this-func 1();} };} }回声(新的outer)-func 2()-func 3();//6匿名函数可以实现闭包,那么相应的匿名类也可以实现闭包
?php/** *由PhpStorm创建*用户: bee *日期: 2016/4/24 *时间: 1:51 */$ arr=array();对于($ I=0;$ i3$i ){ $arr[]=新类($ I){ public $ index=0;function _ _ construct($ I){ $ this-index=$ I;回显“创建/br”;} public function GetVal(){ echo $ this-index;} };} $ arr[2]-GetVal();回声“br”;var _ dump($ arr[1]);运行效果图如下:
更多关于服务器端编程语言(专业超文本预处理器的缩写)相关内容感兴趣的读者可查看本站专题: 《PHP基本语法入门教程》 、 《PHP运算与运算符用法总结》 、 《php面向对象程序设计入门教程》 、 《PHP网络编程技巧总结》 、 《PHP数组(Array)操作技巧大全》 、 《php字符串(string)用法总结》 、 《php+mysql数据库操作入门教程》 及《php常见数据库操作技巧汇总》
希望本文所述对大家服务器端编程语言(专业超文本预处理器的缩写)程序设计有所帮助。
版权声明:PHP7匿名类用法分析是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。