Using an autoload function to make your life easier
Wednesday, October 1st, 2008 at 2:16pm, in Misc, written by Stefan Ashwell
In PHP 5 you can make your life a lot easier by writing an autoload function. This function will automatically load your classes, so you do not need to repeatedly include classes on every page.
It is best to create an autoload function in a file that is included on every page. Typically when I develop a site I like to have a configuration file that I include on every page which does database connections and other site wide operations, so I'll put mine in there.
function __autoload($class) {
require_once 'classes/'.$class . '.php';
}
What the above function will do is run whenever you create a new object and attempt to include the class file for you, on the fly! So now whenever I need to create a new object I just need to do the following, and the class file will be included for me.
$news = new News();
You can expand this function to be a little more intelligent. Firstly by checking that the class file exists, and secondly you may have more than one directory holding class files. This can be done like so:
function __autoload($class) {
$classpath = 'classes/'.$class . '.php';
if ( file_exists($classpath) {
require_once $classpath;
}
$classpath = 'libs/'.$class . '.php';
if ( file_exists($classpath) {
require_once $classpath;
}
I hope you've found this article useful, if you have any comments don't hesitate to leave one!

















There are no comments on this article yet
Please log in to post a comment about this article.