简体   繁体   English

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

[英]Better way to include files [php]

lets say I have four PHP files as such: 可以说我有四个这样的PHP文件:

www/global.php www / global.php

<?php 
function doAwesomeStuff() {}

www/child1.php www / child1.php

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

www/child2.php www / child2.php

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

www/subdirectory/grandchild.php 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() . 就个人而言,我想保持更好的依赖关系跟踪或拥有一个中心包含文件,但是如果失败,总会有include_once()

Note: include_once() and require_once() are both much slower than plain-old include() and require() . 注意: include_once()require_once()都比普通的include()require()慢得多。

In grandchild.php , do this: grandchild.php ,执行以下操作:

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替换include ,以避免在无法包含文件后继续操作(“ require”),并避免多次包含文件(“ once”)。

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

You can use require_once() . 您可以使用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将检查“文件是否已经包含,如果已经包含,则不要再次包含(要求)它”。

我认为您正在寻找require_once

As already mentioned require_once 'includes.php' will do the job RE including too much. 如前所述,require_once'includes.php'将完成RE包括太多的工作。

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. 我一直在尝试使用getcwd()返回路径来帮助您完成需要包含的内容,但是不幸的是,我没有具体的东西可以显示给您。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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