Archive - Originally posted on "The Horse's Mouth" - 2012-08-17 17:40:31 - Graham Ellis
You can load one file of source from within another in PHP using require or include ... and if you do so directly, you need to manage your calls to them, as if you load a class or function twice, PHP will object. The alternatives require_once and inlcude_once are good, but if you keep calling them with a loop they can get rather inefficient, constantly checking if file has been loaded and skipping on if it has. There is a third way ...
If you provide a function called __autoload in your main program, that will be called when you try to create an object in a class which has not been loaded, and you can then "just in time" load the class. Your __autoload will take a single parameter - the name of the class to be loaded. Let's see an example.
Here is a piece of code:
$bob = new roots("Ginger");
print "I have created bob\n";
$bobis = $bob->gettype();
print "Bob is a $bobis tree\n";
and here's what happens when I run it without the class loaded, and without an __autoload
PHP Fatal error: Class 'roots' not found in /var/www/oo/aa.php on line 10
By adding the following __autoload:
function __autoload ($why) {
print ("I don't know about my $why\n");
include("twigs.inc");
}
The result becomes
trainee@brugges:/var/www/oo$ php aa.php
I don't know about my roots
I have created bob
Bob is a Ginger tree
trainee@brugges:/var/www/oo$