PHP __autoload() function

Posted on June 28th, 2008, by Cristian in Development

PHP added several magic methods in PHP5. __autoload(), however, isn’t one of them. But that doesn’t make it any less useful. In fact it’s one of the gems in PHP that I find to be relatively under used. It’s common for PHP applications to break out classes into their own files. This becomes cumbersome when working on large projects as you wind up with numerous include/require calls for any given page. There’s got to be a better way…

What can __autoload() do for you?
Did you know that PHP will call __autoload() if you try to call a function which is not yet defined? You simply have to define it and let it know where to find the class file. Let’s use my example of placing all class definitions inside a models directory with the filename being the same as the class name. Your __autoload() function may look something like this.

function __autoload($className)
{
  require_once "./models/{$className}.php";
}

// Instantiate class with __autoload()
$order = new Order();

Make your code less ugly
If you can’t spare an extra function call here or there then __autoload() may not be for you. Though I would begin to question your reasoning. The upside is that your code could become significantly cleaner and more maintainable. The upside of easy to read code often trumps everything else.

One comment

  1. » PHP __autoload() function on June 29th, 2008 at 1:22 am

Leave a comment

Advertise / Sponsors

Comments RSS Feed

Recent Comments

  • yuci: ok, i solved the problem, but i will search for a better one. i just noticed, hidden div doesnt show itself...
  • yuci: hey, yeah i downloaded well, and i edited a lot this application, and i can say that, it is a wonderful app....
  • Cristian: No, it’s working as I tested.
  • yuci: is link dead, or just some temporary problem? i cant download zip files.
  • Fredrik: I can’t get this to work. It seems to fail at $order->setShippingAmount( $shipping_amount +...