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

CandesTheme $75

Advertise / Sponsors

Post a job. Find one. authenticjobs.com How to Be a Rockstar Freelancer
Comments RSS Feed

Recent Comments

  • Oskar Krawczyk: It’s always nice to hear that someone has joined the right side of the force. Have fun!
  • Michaël Villar: Hi, Great choice. For the home/end key, it’s cmd + left/right arrows. alt + left/right arrows...
  • Astralis: Here’s the fix for the padding issue. Of course, I don’t know what this fix may have broken,...
  • Astralis: The span padding (I believe) in Safari and Chrome don’t work.
  • i8pikachu: This menu doesn’t look so great using Chrome.