Submit Tips/Quickies

Application Architecture : Object Oriented

Class Loader

Submitted By: Michael Kahn
Date: 10/15/00 22:28

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.


Comments:
AlternativeJames Brindle12/03/01 19:15
require_once and include_onceMichael Kahn12/11/00 09:04
RE: Easy alternative... :)Michael Kahn12/11/00 08:53
Easy alternative... :)Hendrik Mans12/10/00 01:11
RE: Very goodMichael Kahn11/03/00 07:05
RE: overheadMichael Kahn11/03/00 06:59
syntax doubtAndré Gonçalves10/31/00 21:59
overheadAndré Gonçalves10/31/00 21:47
Very goodVictor M. Varela10/26/00 05:53
overkillRoman Neuhauser10/23/00 14:49
too complicatedchristian10/23/00 13:42
Great!Brett10/20/00 00:23
 

If you are looking for help, please post on the appropriate forum here. Your questions will be answered much more quickly.

Add A Comment:

Name:

Email:

Subject:

Message:

To reduce spam posts, messages are now manually approved

You are not [logged in]. That means your account will not get credit for this post.