tags:

views:

67

answers:

3

How to include multiple paths when a PHP script is called?

For example, I need to point include_path to multiple directories; inside each directories containing sub directories etc. But I want to include all the php files inside the sub directories as well, so that when my master PHP script can call any methods and objects defined inside the directories.

Any idea?

If possible, I would like to call a function to do it, instead of specifying the root directories and loop through everything inside the directories.

+2  A: 

You might be better off using spl_autoload_register(), to register a callback which PHP will call when it can't find a class you are trying to access. You can then write a function to include the correct file based on the name. Libraries like PEAR tend to do this by splitting the Class name by underscore, and each part corresponds to a directory in its path.

I don't think there is any way that you can get PHP (when including a file) to recursively search the include path until it finds the file (unless you write this logic yourself - I suppose you could write wrappers around require(), include() etc., and call those instead, but I wouldn't).

You could also recursively scan through the directories and add each one to the include path when your script starts, but I think this would make including subsequent files much slower.

Tom Haigh
A: 

you need to separate multiple directories by semicolon

dusoft
use the PATH_SEPARATOR constant instead of the semicolon. only windows uses the semicolon for separating paths.
Philippe Gerber
+2  A: 

It sounds like you want to specify each and every directory in your include_path to allow you to just do

require_once("x.php"); // this is in ./foo/bar
require_once("y.php"); // this is in /docs/utils/
require_once("z.php"); // this is in /some/other/include/path

In which case, don't. That idea is full of lose, and bad for documentation, debugging, and sanity.

If you must, you'd have to write a function to recursively crawl your include directory by hand as part of a bootstrap process, or do it by hand.

Either way, this sounds like a bad idea and isn't a feature for a reason.

Justin Johnson
+1 for "this is a bad idea"
Pascal MARTIN