Parse error: syntax error, unexpected $end in
Autoloader basics
Since this is my first post I’ll keep it nice and simple. While there’s a perfectly good autoloader here it’s quite simple and can be expanded.
A basic autoloader is this:
function __autoload($class_name) { require_once $class_name . '.php'; }
As is said this is pretty basic, but it gets the job done, but this will load all the classes from a single folder, what if you have lots of classes and have them all in different folders? Well we need to modify this function to cope with that. First though is the class names, normally you would do a class like this:
class MyClass { }
In order to have a class loaded from a folder we need to change that class name to include the folder we want it to be part of. So our original class becomes this:
class Bases_MyClass { }
Then we can modify our autoloader to load from folders:
function __autoload($class_name) { $class_name = str_replace('_','/',$class_name); require_once $class_name . '.php'; }
This will now load Bases_MyClass from the file Bases/MyClass.php now that wasn’t so hard, just put an underscore every time you want to use another folder.
| Print article | This entry was posted by clutz on 26/08/2010 at 8:40 pm, and is filed under php. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 1 year ago
Eh? Are you some kind of witch or something? I’m going to report you to the authorities.
about 1 year ago
The authorities already know what I’m doing. They might not like it but we’ve come to an…arrangement.