相对路径和嵌套包括 [英] Relative paths and nested includes

查看:155
本文介绍了相对路径和嵌套包括的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件navbar.php,它在文件夹视图/常规中.它包括一些相对路径文件../controllers/file1.php等.

I have a file navbar.php which is in folder views/general. It includes a few relative path files ../controllers/file1.php etc..

我只能将navbar.php文件包含在同一views/general文件夹中的其他文件中.如果我尝试将其包含在该文件之外的文件中,例如视图/注册,

I can only include the navbar.php file in other files in the same views/general folder. If I try to include it in a file outside that, like views/signup,

navbar.php中包含的包含路径(../controllers/file1.php等)不再相关.

the include paths contained in the navbar.php (../controllers/file1.php etc), won't be relevant anymore.

我该如何解决,所以navbar.php可以在任何地方使用?

How can i solve that, so navbar.php can be used from anywhere ?

推荐答案

我遇到了类似的挑战,并创建了一个文件,该文件定义了我希望能够根据需要调用的所有相关路径的常量.我在所有页面中都包含了此文件(我定义了$ urlRoot,以便它可以在所有环境中工作并且可以在不同的域中移动,等等):

I had a similar challenge and created a single file that defines constants for all the relevant paths that I want to be able to call as-needed. I include this file in all my pages (I define the $urlRoot so that this will work in all environments and is moveable do different domains, etc):

文件:pathData.php(为示例添加了MENUDIR):

File: pathData.php (added MENUDIR for your example):

$baseDir = dirname(__DIR__) . '/';
$rootUrl = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
define('ROOTURL', $rootUrl);
define('BASEDIR', $baseDir);
define('INCLUDES', $baseDir . 'includes/');
define('INCLUDESURL', ROOTURL . 'includes/');
define('JQUERYURL', ROOTURL . 'includes/jquery/');
define('MENUDIR', ROOTURL . 'views/general/');

然后在每个文件中,我都包含一个包含相对目录路径的include文件.例如:

Then in each file, I include that file with an include that includes the relative directory path. For example:

include("pathData.php");
or
include("../pathData.php");
or
include("../../pathData.php); 
etc.

因此,您可以(取决于pathData文件的位置):

So in your case you could (depending on where your pathData file is):

include("../pathData.php");
include(MENUDIR . "navbar.php");
etc...

这篇关于相对路径和嵌套包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆