在php [(!)Warning]中包含一个包含文件的文件

时间:2013-01-23 08:36:12

标签: php path include

  

可能重复:
  PHP: Why such weird behaviour when I include a file from another directory which also includes a file?

我遇到问题,包括包含文件的文件。

  • core.inc.php路径:www/test/includes/core.inc.php

  • 包含在core.inc.php中的文件:include_once ('../../connectdb.php');

  • connectdb.php路径:www/connectdb.php

  • index.php路径:www/test/index.php

  • 在index.php中包含文件:include_once ('included/core.inc.php');

当我运行index.php时,会弹出以下警告:

(!) Warning: include_once(../../connectdb.php): failed to open stream: No such file or directory in G:\wamp\www\test\includes\core.inc.php on line 7

(!) Warning: include_once(): Failed opening '../../connectdb.php' for inclusion (include_path='.;C:\php\pear') in G:\wamp\www\test\includes\core.inc.php on line 7

为了动态改变包含的路径,最佳做法是什么?请帮我解决我的问题。谢谢。

3 个答案:

答案 0 :(得分:4)

为避免此类问题,您可以使用PHP魔术常量__DIR__,它将被当前文件的目录替换。

例如:

include_once(__DIR__ . '/relative/path/to/file-to-include.php'); 

请注意,__DIR__仅适用于PHP 5.3+。在该版本下方,您可以__DIR__

替换dirname(__FILE__) 顺便说一下,autoloading是避免包含混乱的好习惯。

答案 1 :(得分:1)

index.php中包含的文件:include_once ('./includes/core.inc.php');

答案 2 :(得分:0)

index.php中指向core.inc.php的相对路径完全错误。

你说的是:“从index.php的位置,在目录上,就在那里。”但是“www”目录中没有“core.inc.php”文件。

正确的路径是“includes / core.inc.php”:从当前目录“www / test”一个目录到“包含”并且就在那里。

使用__DIR____FILE__魔术常量的任何提及也会起作用,但这是一种不同的方法:它将通过使用相对添加来创建文件的绝对路径。它的工作方式相同,但看起来更复杂。

如果您正在使用类,请尝试实现自动加载。然后您不需要显式包含文件,只需使用类。

相关问题