使用require_one的路径错误


Wrong path using require_once

我在字符串中使用require_one时遇到问题。我指定的路径错误,找不到解决方案。

我有一个名为header.php的文件,通过使用require_one包含两个文件:functions.php和navigation.php。这部分工作正常。当我试图将header.php包含在另一个目录中名为view.php的文件中时,问题就会出现。

这是树木景观:

C:'wamp'www'1.1'plugins'docreader'php'view.php
C:'wamp'www'1.1'theme'dark-blue'templates'files'header.inc.php
C:'wamp'www'1.1'theme'dark-blue'templates'files'functions.inc.php
C:'wamp'www'1.1'theme'dark-blue'templates'files'navigation.inc.php

我尝试了很多不同的道路,但都没有成功。

有人知道线索吗?

阅读(并使用)魔术常数__DIR__和函数dirname(),从includer的路径开始生成包含文件的路径。

例如,如果在plugins'docreader'php'view.php中要包含theme'dark-blue'templates'files'functions.inc.php,则使用以下内容:

// Use this in 'plugins'docreader'php'view.php'
include dirname(dirname(dirname(__DIR__))).
        '/theme/dark-blue/templates/files/functions.inc.php';

__DIR__是一个神奇的常量,它的计算结果是包含使用它的文件的目录。在C:'wamp'www'1.1'plugins'docreader'php'view.php中,__DIR__的值为'C:'wamp'www'1.1'plugins'docreader'php'

函数dirname()返回所提供路径的父目录。有点像..,只是更好。使用它三次将作为参数传递的值(上面解释的__DIR__的值)减少到'C:'wamp'www'1.1'。一切都是直截了当的:添加所需文件('/theme/dark-blue/templates/files/functions.inc.php')的相对路径,忘记包含问题。

您需要将文件路径设置为绝对路径,而不是相对路径。实现这一点的一个有用的超级全局是$_SERVER['DOCUMENT_ROOT'],它将评估您的web服务器文件根。