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 command.
require_once('CommandA.php');
require_once('CommandB.php');
require_once('CommandC.php');
class Interpreter {
// Interprets input and calls the required commands.
}
Is there someway to include all of these commands with a single require_once? I have a similar problem 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 require? Such as:
require_once('*.php');
class Interpreter { //etc }
Is there any other way around this that doesn't involve twenty lines of include at the top of the file?
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.
You can include all files using foreach ()
Store all files name in array.
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:
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
http://php.net/glob
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.