php7 匿名类
匿名类的用处非常大。
1、匿名类可以创建一次性的简单对象。例:
// 使用显性类
class Logger
{
public function log($msg)
{
echo $msg;
}
}
$util->setLogger(new Logger());
// 使用匿名类
$util->setLogger(new class {
public function log($msg)
{
echo $msg;
}
});2、可以传递参数到匿名类的构造器,也可以扩展(extend)其他类、实现接口(implement interface),以及像其它普通类一样使用trait。例:
<?php
class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}
var_dump(new class(10) extends SomeClass implements SomeInterface {
private $num;
public function __construct($num)
{
$this->num = $num;
}
use SomeTrait;
});输出:
object(class@anonymous)#1 (1) {
["Command line code0x104c5b612":"class@anonymous":private]=>
int(10)
}文章版权声明
1、本网站名称:阿V编程
2、本站永久网址:https://www.1892zyw.com
3、本网站的部分文章内容/部分资源可能来源于网络,仅提供给大家学习或参考,如有侵权,请联系站长QQ进行删除处理。
4、本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
5、本站一律禁止以任何方式发布或转载任何违法的相关信息,如有发现请向站长举报
