简体   繁体   中英

Better way to include files [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?

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() .

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").

查看require_once ,这样, 当以前未包含文件时,该文件才包含在内。

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".

我认为您正在寻找require_once

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.

除了require_once部分,您还可以在中央配置文件中使用php的__autoload magic方法来整理代码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM