php包含有没有办法包含仅相对于该文档的文件? [英] php includes is there any way to include a file relative only to that document?

查看:100
本文介绍了php包含有没有办法包含仅相对于该文档的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含inc / footer.php的index.php文件,我会写:

If I have an index.php file that includes inc/footer.php I would write:

include 'inc/footer.php';

如果我想在footer.php中包含另一个文件,我必须相对于索引这样做。 php文件(包含它的那个)。这可能不是问题,但如果我想从整个不同的位置包含index.php呢?

If I want to include another file inside footer.php, I must do it relative to the index.php file (the one that is including it). This may not be a problem, but what about if I want to include index.php from an entire different location?

我知道有几种方法可以实现这一点定义绝对路径或使用dirname( FILE )。

I understand that there are several methods to achieve this like defining an absolute path or using dirname(FILE).

这是从来没有真正的问题,因为我总是这样或那样想通了,但我总是想知道如何在php中完成包含工作。

This is something that has never been a real problem since one way or another I always figured it out but that I always wondered how exactly includes work in php.

有人可以解释一下我在幕后发生了什么事吗?

Can someone explain me exaclty what is going on under the hood?

谢谢

推荐答案

这可能会有所帮助:(来自 http://php.net/manual/en/function.include.php

This may help: (from http://php.net/manual/en/function.include.php)


包含的文件首先在每个include_path条目
中查找相对于当前工作的
目录的
,然后在$ b目录中$ b当前脚本。例如。如果你的
include_path是库,当前的
工作目录是/ www /,你包括
包括/ a.php,并且
包含该文件中的b.php, b.php
首先在/ www / libraries /
中查找,然后在/ www / include /中查找。如果文件名
以./或../开头,则只能在当前工作的
目录或当前
工作目录的父目录中查看

Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is libraries, current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/. If filename begins with ./ or ../, it is looked for only in the current working directory or parent of the current working directory, respectively

您的问题是:


如果我想要包括另一个文件
在footer.php中,我必须相对于index.php文件(
包含它)

If I want to include another file inside footer.php, I must do it relative to the index.php file (the one that is including it).

只有在您尝试 include()的文件路径以 ./ <开头时才会出现这种情况。 / code>或 ../ 。如果您需要使用相对路径在当前文件上方包含文件,则可以(按照建议)使用:

This is true only if the filepath you are trying to include() starts with ./ or ../ . If you need to include a file above the current file using a relative path, you can (as you suggested) use:

include( dirname(__FILE__) . '/../file.php')






如果你定义一个绝对路径,你也可以将它添加到当前的include_path:


If you define an absolute path, you can also add this to the current include_path:

set_include_path(get_include_path() . PATH_SEPARATOR . '/absolute/path');

然后,您可以执行相对于'/ absolute / path /'的所有包含。

You can then do all your includes relative to '/absolute/path/'.

这篇关于php包含有没有办法包含仅相对于该文档的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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