PHP的包含文件在不同的文件夹中,其中包含另一个文件 [英] Php include file in different folder that includes another file

查看:282
本文介绍了PHP的包含文件在不同的文件夹中,其中包含另一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP新手,我一直在尝试使文件(index.php)包含另一个文件(connect.php)和另一个文件(config.php),但它们位于不同的文件夹中.

这是我的目录结构:

 > index.php (in the [root]...)
 > connect.php ([root]/admin/)
 > config.php ([root]/admin/)

这是我到目前为止所拥有的:

index.php

include './admin/connect.php'

connect.php

$directory = getcwd();
chdir(__DIR__);
include "config.php";
chdir($directory);

这实际上是可行的,但是不知何故我不喜欢更改工作目录的想法.

有没有更好的方法可以实现我的目标?

解决方案

您可以将以下几行放在index.php的顶部,

index.php

<?php

// Define native directory seperator. 
define('DS', DIRECTORY_SEPERATOR);

// Define absolute project root.
define('ROOT', getcwd().DS);

// Define absolute admin folder 
define('ADMIN_ROOT', ROOT.'admin'.DS);

include ADMIN_ROOT.'connect.php';

connect.php

<?php

include ADMIN_ROOT.'config.php';

I am new in PHP and I've been trying to make a file (index.php) include another file (connect.php) that includes another file (config.php) but they are located in different folders.

This is my directory structure:

 > index.php (in the [root]...)
 > connect.php ([root]/admin/)
 > config.php ([root]/admin/)

This is what I have so far:

index.php

include './admin/connect.php'

connect.php

$directory = getcwd();
chdir(__DIR__);
include "config.php";
chdir($directory);

This is actually working but somehow I'm not loving the idea of changing the working directory.

Is there a better way to achieve my goal?

解决方案

You can put following lines at top of your index.php,

index.php

<?php

// Define native directory seperator. 
define('DS', DIRECTORY_SEPERATOR);

// Define absolute project root.
define('ROOT', getcwd().DS);

// Define absolute admin folder 
define('ADMIN_ROOT', ROOT.'admin'.DS);

include ADMIN_ROOT.'connect.php';

connect.php

<?php

include ADMIN_ROOT.'config.php';

这篇关于PHP的包含文件在不同的文件夹中,其中包含另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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