I've written a little system that automatically loads classes from the same directory in which it's located the file who require that class.
<?php
function load_class($class_name, $backtrace_level = 1)
{
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $backtrace_level);
$backtrace = array_pop($backtrace);
include_once dirname($backtrace['file']) . '/' . $class_name . '.php';
}
function class_autoloader($class_name)
{
load_class($class_name, 3);
}
spl_autoload_register('class_autoloader');
Now i can include classes in two ways:
- Through spl_autoload_register():
$test_obj = new Base_class;
orTest_class extends Base_class
- Through load_class():
load_class('Base_class');
In both cases the Base_class
should be included from the same directory in which it was required.
E.g.
File /application/models/Extendend_class.php
<?php
class Extended_class extends Base_class {
/* class code... */
}
should automatically include /application/models/Base_class.php
Some say (and I quite agree with them) that using debug_backtrace() in production code is a poor practice, so the question is: there is a way to achieve a similar behaviour without that function?
Thanks in advance.
P.S.
This is the actual script I'm working on.
Update
I tried as suggested with an empty try - catch and it works! It might not be the "cleanest" solution, but it works...
function load_class($class_name, $backtrace_level = 0)
{
try
{
throw new Exception();
}
catch (Exception $e) {}
$backtrace = $e->getTrace();
$backtrace = $backtrace[$backtrace_level];
include_once dirname($backtrace['file']) . '/' . $class_name . '.php';
}
function class_autoloader($class_name)
{
load_class($class_name, 2);
}
spl_autoload_register('class_autoloader');
Update 2
The best way to autoload classes is probably through namespaces.
This is a sample implementation.