PHP 7匿名类

时间:2015-10-28 12:55:37

标签: php anonymous-class php-7

PHP 7引入了一个名为匿名类的新类功能,它允许我们创建对象而无需命名它们。匿名类可以嵌套。您对内存消耗,执行时间,性能问题有何看法?是否有可用的指标/统计数据?

1 个答案:

答案 0 :(得分:5)

Anonymous classes are classes without programmer declared names, they are otherwise identical to normal classes.

Syntax allows them to be nested, just like functions:

function name() {
    function sub() {

    }
}

But just as the code above contains two globally accessible functions, the following code still contains two globally accessible classes:

class C {
    function method () {
        return new class{};
    }
}

It gives you a kind of control over where the class is easily accessible from, in that sense they are nested.

They are not nested in the sense that an anonymous class declared inside another class is not able to access any members of the creating class.

So that this:

class C {
    private $member;

    public function method() {
        return new class {
            public function method() {
                return $this->member;           
            }
        };
    }
}

Is not valid, because the anonymous class is not truly nested.