How to create an "include all" file?

233 Views Asked by At

I would like to create "include all" file, and then from each "real" file instead of including bunch of files each time, include just created "include all" file.

Take a look at the example -- inc.php:

<?php
require_once('A/a.php');
require_once('A/B/b.php');
?>

A/a.php:

<?php
require_once('../inc.php'); 
?>

A/B/b.php:

<?php
require_once("../../inc.php");
?>

However it does not work -- if I execute "a.php" I got error that "inc.php" is not found included from "b.php", and when executing "b.php" per analogy from "a.php".

I don't see what is wrong with my code -- how to solve it?

4

There are 4 best solutions below

1
On BEST ANSWER

If you are using OOP, definitely go for autoloading, as suggested by cjhill.

However if you are doing something less organized, and need to include files manually, I would suggest always using the __DIR__ constant when specifying the include path. That way include paths will be relative to the file they are defined in, rather than the entry-point file.

include_once __DIR__ . "/../../includes.php".

You should think of "include" as a copy-paste, simply dropping the code from the included file into the position of the include call. As such, file paths within the included file will be relative to the originally requested file, unless you specify absolute paths, using something like __DIR__.

See Magic Constants in the manual for details.

2
On

You should look into autoloading in PHP to automatically include any class that hasn't already been included. It's very helpful: PHP Manual

Also, here is a quick tutorial I wrote on the subject.


Alternatively, you could create a global PHP file (global.php) and just include that on every page. In the global.php it include_once all the files you need. But, like I said, method above is preferential.

1
On

You have a loop. File A/a.pho is being included into file inc.php so why have an require at the top of file A/a.php for inc.pho?

The require function q the file in the parenthesis into the file the function is called from.

File A/a.php and A/B/B.php will inherit all scope data from inc.php upon their appendment into inc.php

1
On

A good way is to use an absolute path like this :

Php < 5.3 :

require_once(dirname(__FILE__) . '../inc.php');

Php 5.3 :

require_once(__DIR__. '../inc.php');