You are here

Nested or Inner Classes in PHP

Inner Class Simulation in PHP with Nested Anonymous Objects and Closures

Emulating Inner Classes in PHP Using Closures and Anonymous Objects

By Arlon Arriola

While PHP doesn’t support true nested or inner classes, it’s possible to simulate them cleanly using a combination of (object)[...] and closure functions. This approach enables modular, inner-structured behavior — much like inner classes or nested objects in other languages — using nothing more than native PHP 7 syntax.

Working Pattern

The pattern revolves around defining inner “objects” inside the constructor of the main class using PHP's anonymous object syntax. Closures are used to retain access to the parent object context, allowing internal referencing across nested layers.

class User {
  public $id;
  public $name;
  public $password;
  public $Profile;
  public $History;

  public function __construct($id, $name, $password) {
    $this->id = $id;
    $this->name = $name;
    $this->password = $password;

    $this->Profile = (object)[
      'get' => function() {
        return 'Name: ' . $this->name . '' . (($this->History->get)());
      }
    ];

    $this->History = (object)[
      'get' => function() {
        return ' History: ' . (($this->History->track)());
      },
      'track' => function() {
        return (lcg_value() > 0.5 ? 'good' : 'bad');
      }
    ];
  }
}

echo ((new User(0, 'Anonymous', 'password'))->Profile->get)();

Output (example):

Name: Anonymous History: good

Why This Works

  • Closures capture context: Inner functions retain access to $this from the outer class.
  • No special syntax needed: All objects are created using (object)[...], avoiding class definitions entirely.
  • Safe in PHP 7+: Tested successfully in PHP 7.1.33 — no syntax errors, no reflection, no hacks.

This is an elegant workaround to PHP’s lack of true inner class syntax — keeping the logic encapsulated inside the class without requiring separate files or scaffolding.

Deeper Nesting: Multi-Level Inner Objects

This model scales — you can nest as deeply as needed by building object trees. Here’s an example with four levels of nesting:

class InnerDemo {
  public function __construct() {
    $this->Writing = (object)[
      'Files' => (object)[
        'ThirdLevel' => (object)[
          'FourthLevel' => (object)[
            'write' => function($_what, $_where, $_append) {
              $Handle = $_append ? fopen($_where, 'a') : fopen($_where, 'w');
              fwrite($Handle, $_what);
              fclose($Handle);
            }
          ]
        ]
      ]
    ];
  }
}

((new InnerDemo())->Writing->Files->ThirdLevel->FourthLevel->
      write)('Four levels of inner classes!', 'tester.html', true);

This will append the string Four levels of inner classes! to a file named tester.html.

Use Cases

  • Simulating nested services or domain layers
  • Encapsulating complex behavior inside structured trees
  • Building inline, lightweight service containers
  • Organizing logic by responsibility without creating full class hierarchies

Conclusion

This is a lightweight, expressive way to build nested behaviors in PHP. You get the benefits of inner class-style encapsulation, functional closures, and object references — all without leaving the class context or writing separate files.

Perfect for developers who want modular structure without OOP boilerplate. This technique embraces PHP’s strengths, bypasses its limitations, and keeps everything neatly scoped.


For further discussion and context, please also see the original Stack Overflow thread:
Nested or Inner Class in PHP (stackoverflow.com)

Posted by Arlon Arriola · Santa Cruz Web Factory

Subscribe to RSS - Nested or Inner Classes in PHP

You are here