Funny this. One of those things where you do a bit of surfing to find the easy answer. The resulting pages of your search contain the name of the solution you are looking for in the title, but the containing code solves a different problem.
So, here is the problem.
I am creating a PHP application which has multiple directories containing classes will need throughout it's build.
I want to use the PHP __autoload function.
I will need 2 PHP files to support this activity, but below this I will show how they are called.
First file, config.php. This will contain a class containing all the support data needed throughout my application.
<?php
class supportdata
{
public $supportArray = array('lib', 'helper');
}
?>
There. Not too difficult was it.
Next, my autoload.php.
<?php
require_once 'config.php';
function __autoload($class_name)
{
$sd = new supportdata;
$classString = '';
foreach($sd->supportArray as $value)
{
$classString = $DOCUMENT_ROOT.$value.'/'.$class_name.'.php';
if(file_exists($classString))
{
require_once $classString;
}
}
}
?>
As you can see it calls config.php and makes use of the supportArray to iterate through the directories, checking to see if the class exists. If it does we do a require_once on it.
Now, here is how my autoloading is called.
<?php
include_once 'autoload.php';
class index
{
function __construct()
{
}
}
new index;
?>
In my index class I can now call any of the classes contained in the directories named in config.php. In fact, I can call any of the those classes, anywhere in my application.
No comments:
Post a Comment