Anonymous Classes in PHP 7


Staff member
May 28, 2020
United States
A feature that exists in many programming languages and was added to PHP with the release of PHP 7 is anonymous classes. If you read my forum post on C# Classes you are aware that classes are necessary because they ensure consistent behavior across objects. In the event you do not want a separate class definition (for example the class is only instantiated in one place in your entire program) anonymous classes may suit your use case better. Since anonymous classes are written similarly to regular named classes, they're easy to convert to a named class later on if you decide the class is needed in multiple places.

You can write an anonymous class as follows...
    $name = "Catgirl";
    $age = 21;
    $person = new class($name, $age) {
        private $name;
        private $age;
        public function __construct($name, $age) {
            $this->name = $name;
            $this->age = $age;

You can then access the object as if it's a member of a named class. There are a few limitations to keep in mind with anonymous classes:
  • They can only be used once. If you need to use it in multiple places you'll have to turn it into a regular class.
  • They cannot be serialized.
  • Nesting an anonymous class within a named or other anonymous class will hide the outer classes protected and private methods from it. You can pass the values from the outer class through the constructor although this is poor class design and should be avoided.
Despite these limitations anonymous classes can improve code readability, assist with mock testing, and for inline class overrides.

What do you think about this PHP feature? Will you continue to use named classes or will you start using anonymous classes in certain parts of your programs?