Including a whole directory in PHP or Wildcard for use in PHP Include?

后端 未结 5 530
粉色の甜心
粉色の甜心 2021-01-12 07:30

I have a command interpreter in php. It lives inside the commands directory and needs access to every command in the command file. Currently I call require once on each co

相关标签:
5条回答
  • 2021-01-12 07:46

    It's 2015 now, so you're most likely running PHP >= 5. If so, as mentioned a couple of times above, PHP's autoload capability is a good solution, probably the best. It was created specifically so you won't have to write a utility function for auto loading. However, as mentioned in the PHP docs, __autoload is no longer recommend and may be depreciated in future versions. As long as you're using PHP >= 5.1.2, use spl_autoload_register instead.

    0 讨论(0)
  • 2021-01-12 07:51

    Why do you want to do that? Isn't it a better solution to only include the library when needing it to increase speed and reduce footprint?

    Something like this:

    Class Interpreter 
    {
        public function __construct($command = null)
        {
            $file = 'Command'.$command.'.php';
    
            if (!file_exists($file)) {
                 throw new Exception('Invalid command passed to constructor');
            }
    
            include_once $file;
    
            // do other code here.
        }
    }
    
    0 讨论(0)
  • 2021-01-12 07:56

    You can't require_once a wildcard, but you can programmatically find all the files in that directory and then require them in a loop

    foreach (glob("*.php") as $filename) {
        require_once($filename) ;
    }
    

    http://php.net/glob

    0 讨论(0)
  • 2021-01-12 07:58

    You can include all files using foreach ()
    Store all files name in array.

    $array =  array('read','test');
    
    foreach ($array as $value) {
        include_once $value.".php";
    }
    
    0 讨论(0)
  • 2021-01-12 08:04
    foreach (glob("*.php") as $filename) {
        require_once $filename;
    }
    

    I'd be careful with something like that though and always prefer "manually" including files. If that's too burdensome, maybe some refactoring is in order. Another solution may be to autoload classes.

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