包含文件的更好方法[php]

lets say I have four PHP files as such:

www/global.php

<?php 
function doAwesomeStuff() {}

www/child1.php

<?php
include ("global.php");
function Something1() {}

www/child2.php

<?php
include ("global.php");
function Something2() {}

www/subdirectory/grandchild.php

<?php
include ("../global.php");
include ("../child2.php");
function Something3() {}

I run into the problem of including global twice in one case, but if we keep getting complicated, the include's are calling directory paths relative to the called file, not the included file, which is a real pain logically.

Any solutions to this?

In grandchild.php, do this:

set_include_path("..");
require_once("global.php");
require_once("child2.php");

And in all the other files, it's better to replace include with require_once, too, to avoid going on after not being able to include a file ("require") and to avoid including a file multiple times ("once").

Personally, I'd say keep better track of dependencies or have a central includes files, but failing that, there's always include_once().

Note: include_once() and require_once() are both much slower than plain-old include() and require().

You can use require_once(). Ofcourse it's better to make a solid dependecy of the files. But require_once will check "if the file has already been included, and if so, not include (require) it again".

I think you are looking for require_once

Look at require_once, this way a file it's included only if it has not been included before.

As already mentioned require_once 'includes.php' will do the job RE including too much.

I have played around with using getcwd() to return the path to help with what you need to include but I have nothing concrete to show you unfortunately.

In addition to the require_once part, you can probably neaten up your code a bit using php's __autoload magic method in a central config file.