如何在require_once中包含路径解析? [英] How does include path resolution work in require_once?

查看:464
本文介绍了如何在require_once中包含路径解析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我遇到一个奇怪的情况时,我正在用PHP编写一个Web应用程序。为了说明我的问题,请考虑这种结构的Web应用程序:

I was writing an web app in PHP, when I encountered a strange situation. To illustrate my problem, consider a web app of this structure:

/
    index.php
    f1/
        f1.php
    f2/
        f2.php

这些文件的内容:

index.php:

index.php:

<?php require_once("f1/f1.php"); ?>

f1.php:

<?php require_once("../f2/f2.php"); ?>

f2.php:空白

现在当我尝试在浏览器中打开index.php时出现此错误:

now when I try to open index.php in my browser I get this error:

Warning: require_once(../f2/f2.php) [function.require-once]: 
failed to open stream: No such file or directory in /var/www/reqtest/f1/f1.php on line 2
Fatal error: require_once() [function.require]: 
Failed opening required '../f2/f2.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/reqtest/f1/f1.php on line 2

有什么明显的东西我不见了?如何在PHP中包含路径?

Is there something obvious I'm missing? how do include paths work in PHP?

在我提出这个问题之前,我试图进行实验并找出答案。我设置了另一个测试,如下所示:

Before I asked this question, I attempted to experiment and find out. I set up another test, like so:

/
    index.php
    f1/
        f1.php
        f2.php

index.php:

index.php:

<?php require_once("f1/f1.php"); ?>

f1.php:

<?php require_once("f2.php"); ?>

f2.php:blank

f2.php: blank

To我的意外(并且完全混乱),这很好!

To my surprise (and utter confusion), this worked out fine!

那么,路径解析背后的秘诀是什么?

So, what is the secret behind the path resolution?

PS我看到了这个问题,但它仍然没有回答我在这里所说的第二个案例。

PS I saw this question, but it still does not answer the second case that I've stated here.

推荐答案

如果包含另一个文件,工作目录仍然是包含文件的位置。

If you include another file, the working directory remains where the including file is.

您的示例按预期工作。

编辑:第二个示例有效,因为。 (实际目录)位于您的包含路径中(请参阅您的错误消息)。

The second example works because . (actual directory) is in your include path (see your error message).

编辑2:
在您的第二个示例中,你感兴趣的关键点是这一行:

In your second example, the key point of your interest is this line:

<?php require_once("f2.php"); ?>

首先它将查看当前工作目录( / var / www / req_path_test ),但找不到f2.php。

At first it will look in the current working dir (/var/www/req_path_test), but does not find f2.php.

作为后备,它会尝试在你的include_path中找到f2.php('。:/ usr / share / php:/ usr / share / pear'),以'。'开头(相对于实际文件,而不是包括一个。)

As fallback, it will try to find f2.php in your include_path ('.:/usr/share/php:/usr/share/pear'), starting with '.' (which is relative to the actual file, not the including one).

所以'./f2.php'有效且要求不会失败。

So './f2.php' works and the require does not fail.

这篇关于如何在require_once中包含路径解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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