使路径可在PHP的各个级别的文件夹中访问 [英] Make path accessible at various level of folder on PHP
问题描述
假设我有一个文件夹,上面有一些文件夹和页面:
Assume that I have a folder with some folders and pages on it:
- 文件夹A
- PageA1.php
- FolderA
- PageA1.php
- 文件夹B1
- PageB11.php
- FolderB1
- PageB11.php
- PageB21.php
- PageC1.php
在 PageB11 上,我有:
require_once 'FolderB2/PageB21.php';
在 PageB1 上调用 PageB11 时:
require_once 'FolderB1/PageB11.php';
一切正常.但是现在的问题是,在 PageB11 上也有一个调用页面本身的函数( PageB11 ),然后显示错误:
It's work fine. But now the problem is, while on PageB11 also have a function that call the page itself (PageB11), then the error showed:
Warning: require_once(FolderB2/PageB21.php): failed to open stream: No such file or directory in Path\FolderB\FolderB1\PageB11.php on line X
当我将 PageB11 上的require_once行更改为:
require_once '../FolderB2/PageB21.php'
;时,就可以了!When I changed the require_once line on PageB11 become:
require_once '../FolderB2/PageB21.php'
;, it's work!我想做的是,如何使所有这些文件都可以在不同级别的文件夹中访问?有可能做到这一点吗?谢谢.
What I wanna do is, how to make all of it accessible at various level of folder? Is is possible to do that? Thanks..
推荐答案
如上所述,处理此类情况的最佳方法是通过其绝对路径引用每个文件.这是从文件系统根目录开始的路径,这与当前文件相对指定的相对路径不同.
As stated, the best way of handling such situations, is to refer to each file by its absolute path. This is the path from the root of the filesystem, unlike a relative path which is given relative by the current file.
在PHP中,您有一个神奇的常量
__DIR__
,它提供了当前文件的绝对路径.在每个include/require之前加上这个,您将再也不会遇到该问题.In PHP you have a magical constant
__DIR__
, which gives the absolute path of the current file. Prepend every include/require with that, and you'll never see that problem again.require_once __DIR__ . '/../FolderB2/PageB21.php';
您还可以使用
realpath()
.You can also make use of
realpath()
.这篇关于使路径可在PHP的各个级别的文件夹中访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!