Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question
    
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 at 1:07

1 Answer 1

up vote 6 down vote accepted

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);
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.