#native_company# #native_desc#
#native_cta#

Class Loader

By Michael Kahn
on October 15, 2000

I’m fairly new to PHP, but come from a background in Java and Perl. One of the nuisances I found with PHP4 (the version I started in) is the following error generated when includeing or requireing the same class file across multiple files containing subclasses, one or more of which may be used during the execution of a PHP script:

Fatal error: Cannot redeclare class mywidgetclass in Unknown on line 5

I’m used to componentizing my work into reusable classes which have some sort of import (java) or use (perl) declarations that can load required classes, but which avoid doing so if the class is already loaded. I’d also like to avoid the overhead of preloading any and all base classes “just-in-case” in my auto_prepend file.

My solution is to put each class in its own class.{classname}.inc file, and have the following in my auto_prepend file:

// class loader
class ClassLoader {
        var $loaded = array();
        
        function load($class,$base="") {
                global $CLASSLOADER;
                if (!$this->loaded[$class]) {
                        if ($base) {
                                include("$base/class.$class.inc");
                        }
                        else {
                                include("class.$class.inc");
                        }
                        $this->loaded[$class]  = true;
                        return true;
                }
                return false;
        }
}
$CLASSLOADER = new ClassLoader();

This allows me to put redundant $CLASSLOADER->load(“{classname}”) calls to local or remote (http-based) code bases at the top of my class files without worrying about the redeclaration error. Well, the error will still occur if other php code is used that simply includess the class, but I make an effort not to load an class.{classname}.inc files that way.