按相对路径包含文件 [英] Including files by relative path

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

问题描述

关于链接文件肯定有一些我不明白的事情 - 但这是我的问题。

There must be something i don't understand about linking files -- but here's my problem.

基本上,我有三个文件。

Basically, i have three files.


  1. generalfunctions.php

  2. wordcount.php

  3. index.php

所有三个文件都在不同的目录中。

All three files are in different directories.

B依赖于A,如下所示: ../../../ phpfunctions / generalfucntions.php

当我跑B时一切都很好。

B relies on A as follows: ../../../phpfunctions/generalfucntions.php
And when I run B all is well.

但C依赖B如下: ../ wordcount.php

当我运行C时,我收到一条错误消息,指出无法找到链接文件A.

When I run C, I get an error saying that linked file A cannot be found.

实际错误是:


第11行的/.../public_html/plaoul/text/statistics/wordcount.php中没有此类文件或目录

No such file or directory in /.../public_html/plaoul/text/statistics/wordcount.php on line 11

任何想法我做错了吗?

感谢您的帮助。

推荐答案

当您使用 include t时o包含一个文件,并使用相对路径作为参数,它将相对于当前工作路径

When you use include to include a file, and you use a relative path as parameter, it will be relative to the current working path.

目前的路径是什么?它通常是第一个调用PHP脚本的路径。整个执行开始的脚本。您可以使用函数 getcwd 获取当前工作目录。例如:<?php echo getcwd(); ?> 会显示当前工作路径。您可以使用 chdir 函数更改当前工作路径。例如:<?php chdir('/ home / myself'); ?> - 使用此命令,您只需更改当前的工作路径!

What is the current path? It is normally the path of the first called PHP script. The script where the whole execution started. You can get the current working dir with the function getcwd. For example: <?php echo getcwd(); ?> will show you the current working path. You can change the current working path using the chdir function. For example: <?php chdir( '/home/myself' ); ?> - with this command you just changed the current working path!

因此,使用相对并不总是好的包含中的路径,因为当前路径可能会更改。

So, it is not always good to use relative paths in include, because the current path MAY change.

但是使用了 __ FILE __ 魔术常量您可以使用某种相对路径作为包含的参数,使其成为相对于include命令的文件。这很好!因为无论当前工作路径是什么,include都将始终相对于包含的文件!

But with the usage of the __FILE__ magic constant you can use a sort of relative path as a parameter for an include, making it relative to the file where the include command is. This is good! Because no matter what the current working path is, the include will be always relative to the file which is including!

所以...尝试以下内容:

So... try the following:

在B中,您应该包含A,如下所示:

In B you should include A as follows:

include( dirname( __FILE__ ) . '/../../../phpfunctions/generalfunctions.php' );

在C中你应该包括B如下:

In C you should include B as follows:

include( dirname( __FILE__ ) . '/../wordcount.php' );

简而言之:使用 dirname(__FILE__)您可以使用相对于include命令所在文件的路径来包含该文件。否则,路径将相对于当前工作路径。

In short: using dirname( __FILE__ ) you can include the file using a path relative to the file where the "include" command is. Otherwise, the path will be relative to the current working path.

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

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