Include full catalog in PHP or Wildcard for use in PHP Include?

I have a command interpreter in php. It lives inside the command directory and needs access to each command in the command file. I am currently calling the request once for each command.

require_once('CommandA.php'); require_once('CommandB.php'); require_once('CommandC.php'); class Interpreter { // Interprets input and calls the required commands. } 

Is it possible to include all these commands with one require_once? I have a similar problem with many other places in my code (with factories, builders, other interpreters). There is nothing but commands in this directory, and the interpreter needs every other file in the directory. Is there a wildcard that can be used in a requirement? For example:

 require_once('*.php'); class Interpreter { //etc } 

Is there another way that doesn't include twenty include lines at the top of the file?

+6
include php wildcard require
source share
5 answers

Why would you want to do that? Isn’t this the best solution to include a library only if it needs to increase speed and decrease track?

Something like that:

 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. } } 
+4
source share
 foreach (glob("*.php") as $filename) { require_once $filename; } 

I would be careful with something similar, although I always prefer "manually", including files. If it's too burdensome, maybe some refactoring is fine. Another solution might be startup classes .

+18
source share

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

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

http://php.net/glob

+7
source share

You can include all files using foreach ()
Store all file names in an array.

 $array = array('read','test'); foreach ($array as $value) { include_once $value.".php"; } 
+2
source share

Now is 2015, so you are most likely using PHP> = 5. If this is the case, as mentioned several times above, the ability to autoload PHP is a good solution, probably the best. It was created specifically, so you do not have to write a utility function for automatic loading. However, as mentioned in the PHP docs, __ autoload is no longer recommended and may be discounted in future versions. While you are using PHP> = 5.1.2, use spl_autoload_register instead .

0
source share

All Articles