PHP, How to set include path

Common practice is to have a "common.php" or "includes.php" file that includes the include/include_once calls (for the sake of simplicity). e.g.

  • root
  • [lib]
    • a.php
    • b.php
    • includes.php
  • index.php

Then includes.php contains:

<?php
  include_once('a.php');
  include_once('b.php');
?>

Then in any script it's a matter of including the includes.php file.

However, to answer your original question, you can only include one file at a time, per call. You can use something like opendir and readdir to iterate over all files in a specific directory and include them as found (automated so-to-speak) or write out each include yourself based on the files you're creating.

Also, all setting the include path does is set a directory to look in when an include call is made. It's not a directory where the files should automatically be loaded (which is the impression I get from your post).


Setting the include_path will not include every file in that directory, it only adds that directory to the list PHP will search when including a file.

Specifies a list of directories where the require(), include(), fopen(), file(), readfile() and file_get_contents() functions look for files.

Source

This would simplify including files in a deep structure or in a completely different section of the filesystem.

include('/var/somewhere/else/foo.php');

With /var/somewhere/else/ added to the php.ini include_path could become

include('foo.php');

Additionally, as others pointed out, there are common practices but you could look into OOPHP and autoloading classes. This will not work for functions that I know of.

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

Tags:

Php

Include

Path