2

可能重复:
PHP:当我包含另一个目录中的文件时,为什么会出现这种奇怪的行为?

我在包含一个包含文件的文件时遇到问题。

  • 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

为了动态地更改包含的路径,最佳实践是什么?请帮我解决我的问题。谢谢你。

4

3 回答 3

4

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

例如:

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

请注意,这__DIR__仅适用于 PHP 5.3+。在该版本以下,您可以替换__DIR__dirname(__FILE__)

顺便说一句,自动加载是避免包含混乱的好习惯。

于 2013-01-23T08:41:08.823 回答
1

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

于 2013-01-23T08:39:09.323 回答
0

您在 index.php 中指向 core.inc.php 的相对路径是错误的。

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

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

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

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

于 2013-01-23T09:11:21.583 回答