Lazy Loading PHP Subclasses as Attributes

Today I began writing a set of classes to consume a SOAP service. The classes are growing in strength, and with performance, and scalability in mind, I decided to auto-load the classes. The object structures are as follows:

  • MainClass
  • MainClassNameSpace
    • ChildClass
    • ChildClassNamespace
      • GrandChildClass
    • ChildClass2
    • ChildClass2Namespace
      • GrandChild2Class

The MainClass contains calls to some of the SoapClient classes I've written, but the objects are the part I want to lazy load. Here's an example: 

$cls = new MainClass($someParameters)

$collection_of_grand_child_classes = $cls->ChildClass->getGrandChildren();
$collection_of_grand_child2_classes = $cls->ChildClass2->getGrandChildren()

Let's say I'm calling $cls->ChildClass2, but I don't want to use up the memory space to load Childclass.

To implement this, I've used the __autoload() magic function of php. 

function autoload($full_namespace) {

$full_namespace = str_replace('\\', '/', $full_namespace);

try {

$file = dirname($_SERVER['SCRIPT_FILENAME']) . '/inc/' . $full_namespace . '.php';
if(file_exists($file)) {

require $file;

} else { 

throw new Exception('Could not autoload class: ' . $full_namespace);

} catch (Exception $ex) {
return $ex->getMessage();

function __construct() { 

This dynamically finds the class, and then loads their include files when they are called, and thus defines the class. They are, unfortunately, still not instantiated, unless I call their constructor. To get around this, I define an array of child objects : 

private $_objects = array(); 

I then you use the magic function __get() to create the object: 

public function __get($var) { 
if(!isset($this->_objects[$var])) { 
$class = get_class() . '\\' . $var;
$this->_objects[$var] = new $class($this);

return $this->_objects[$var];