# Autoloader functions

Every time I write a new PHP page, I usually need to include this at the top:

<?php

require_once(__DIR__ . '/../libraries/global.lib.php');

function load_classes($class) { // appears to get all the names of the classes that are needed in this script...$file_name = './classes/' . $class . '.class.php'; if (file_exists($file_name)) {
require_once($file_name); } } function load_interfaces($interface) {
$file_name = './classes/' .$interface . '.interface.php';
if (file_exists($file_name)) { require_once($file_name);
}
}

spl_autoload_register('load_interfaces');
spl_autoload_register('load_classes');

?>


Is there any way to condense this? Would putting this in a separate PHP file work?

-
Moving this to an include would work. You will have to be careful about paths like __DIR__ since they apply directly to the file they are contained in. – willoller Mar 10 '14 at 1:07

## 1 Answer

Yes, you could put that into a separate file and include_once('header_file.php');.

You try something such as:

function loadFile($name,$isInterface = false) {
$type = ($isInterface == true) ? 'interface' : 'class'
$path = sprintf('./classes/%s.%s.php',$name,$type); if (file_exists($path)) {
require_once(\$path);
}
}

-