Autoload Objects in PHP5

/autoload-objects-in-php5 2007-09-26T11:11:16+01:00

I was reading through Derek Sivers' article on why he switched back to PHP after slogging away are Ruby on Rails for two years, when I stumbled upon something I didn't know and have actually been looking for (though I haven't put much effort into it yet)... autoloading objects in PHP.

To my surprise, I've just discovered that PHP 5 introduced just this functionality with the advent of the __autoload() function.

To quote the PHP documentation...

In PHP 5, [...] You may define an __autoload function which is automatically called in case you are trying to use a class which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

And the implementation is pretty simple too. Once again, drawing from the PHP documentation, you use the function as follows:

          <?php
          function __autoload($class_name) {
              require_once $class_name . '.php';
          }

          $obj  = new MyClass1();
          $obj2 = new MyClass2();
          ?> 

Effectively this will attempt to load the MyClass1 and MyClass2 classes from files names MyClass1.php and MyClass2.php respectively.

As you can imagine, this function can be further enhanced with additional code, and there are some examples in the notes on the __autoload() documentation page in the PHP docs.

Copyright © 2005 - 2018 Colin Seymour All rights reserved. Privacy Policy.
Check out the feed if you do the RSS/Atom thing.