Best way to include file in PHP?

前端 未结 2 1588
醉话见心
醉话见心 2021-01-01 02:45

I\'m currently developping a PHP web application and I would like to know what is the best manner to include files (include_once) in a way where the code it is still maintan

相关标签:
2条回答
  • 2021-01-01 03:08

    It depends on what you are trying to accomplish exactly.

    If you want to have a configurable mapping between files and the directories in which they reside you need to work out a path abstraction and implement some loader functions to work with that. I 'll do an example.

    Let's say we will use a notation like Core.Controls.Control to refer to the (physical) file Control.php which will be found in the (logical) directory Core.Controls. We 'll need to do a two-part implementation:

    1. Instruct our loader that Core.Controls is mapped to the physical directory /controls.
    2. Search for Control.php in that directory.

    So here's a start:

    class Loader {
        private static $dirMap = array();
    
        public static function Register($virtual, $physical) {
            self::$dirMap[$virtual] = $physical;
        }
    
        public static function Include($file) {
            $pos = strrpos($file, '.');
            if ($pos === false) {
                die('Error: expected at least one dot.');
            }
    
            $path = substr($file, 0, $pos);
            $file = substr($file, $pos + 1);
    
            if (!isset(self::$dirMap[$path])) {
                die('Unknown virtual directory: '.$path);
            }
    
            include (self::$dirMap[$path].'/'.$file.'.php');
        }
    }
    

    You would use the loader like this:

    // This will probably be done on application startup.
    // We need to use an absolute path here, but this is not hard to get with
    // e.g. dirname(_FILE_) from your setup script or some such.
    // Hardcoded for the example.
    Loader::Register('Core.Controls', '/controls');
    
    // And then at some other point:
    Loader::Include('Core.Controls.Control');
    

    Of course this example is the bare minimum that does something useful, but you can see what it allows you to do.

    Apologies if I have made any small mistakes, I 'm typing this as I go. :)

    0 讨论(0)
  • 2021-01-01 03:20

    I used to start all my php file with:

    include_once('init.php');
    

    Then in that file I would require_once all the other files that needed to be required, like functions.php for example, or globals.php where I would declare all global variables, or constants. That way you only have to edit all your setting at one place.

    0 讨论(0)
提交回复
热议问题