Anonymous Classes

suggest change

Anonymous classes were introduced in PHP 7 so that quick one-off objects can be created easily. They can take constructor arguments, extend other classes, implement interfaces, and use traits, just as normal classes can.

In its most basic form, an anonymous class looks like the following:

new class("constructor argument") {
    public function __construct($param) {
        var_dump($param);
    }
}; // string(20) "constructor argument"

Nesting an anonymous class inside of another class does not give it access to private or protected methods or properties of that outer class. The anonymous class can reach protected methods and properties of the outer class by extending that class. It does not see the outer instance's property values unless they are passed in. Private properties of the outer instance can be passed through the anonymous class’s constructor.

For example:

class Outer {
    private $prop = 1;
    protected $prop2 = 2;

    protected function func1() {
        return 3;
    }

    public function func2() {
        // passing through the private $this->prop property
        return new class($this->prop) extends Outer {
            private $prop3;

            public function __construct($prop) {
                $this->prop3 = $prop;
            }

            public function func3() {
                // accessing the protected property Outer::$prop2
                // accessing the protected method Outer::func1()
                // accessing the local property self::$prop3 that was private from Outer::$prop
                return $this->prop2 + $this->func1() + $this->prop3;
            }
        };
    }
}

echo (new Outer)->func2()->func3(); // 6

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents