php 如何使用__dir__?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32537477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use __dir__?
提问by JosefPP
I want to use __dir__
.
我想用__dir__
.
However, I can't find any good tutorial on how to set it up. I have my htdocs in Dropbox.
但是,我找不到关于如何设置它的任何好的教程。我在 Dropbox 中有我的 htdoc。
Does it work something like this?
它的工作原理是这样的吗?
define(__DIR___, 'd:documents/dropbox/yolo/swag/htdocs/myproject/test/newtest/
testphp/test_new/testincludes/1/new_folder/')
That is the directory where my project is located and it has sub folders. I want to include a file into another file that is in the parent folder.
那是我的项目所在的目录,它有子文件夹。我想将一个文件包含到父文件夹中的另一个文件中。
Should I then just type:
我应该输入:
include'__DIR__/warlock.php';
Or do I have to type something like this?
或者我必须输入这样的东西吗?
include '___DIR__/wow/newb/guidesfornabz/classes/casters/warlock.php';
回答by Howl
You can use __DIR__
to get your current script's directory. It has been in PHP only since version 5.3, and it's the same as using dirname(__FILE__)
. In most cases it is used to include another file from an included file.
您可以使用__DIR__
来获取当前脚本的目录。它仅在 PHP 5.3 版本后才出现,并且与使用dirname(__FILE__)
. 在大多数情况下,它用于从包含的文件中包含另一个文件。
Consider having two files in a directory called inc
, which is a subfolder of our project's directory, where the index.php
file lies.
考虑在名为 的目录中有两个文件,该目录inc
是我们项目目录的子文件夹,index.php
文件所在的目录。
project
├── inc
│?? ├── file1.php
│?? └── file2.php
└── index.php
If we do include "inc/file1.php";
from index.php
it will work. However, from file1.php
to include file2.php
we must do an include relative to index.phpand not from file1.php
(so, include "inc/file2.php";
). __DIR__
fixes this, so from file1.php
we can do this:
如果我们这样做include "inc/file1.php";
,index.php
它将起作用。然而,从file1.php
到包含file2.php
我们必须做一个相对于 index.php而不是 from file1.php
(so, include "inc/file2.php";
) 的包含。__DIR__
解决了这个问题,所以file1.php
我们可以这样做:
<?php
include __DIR__ . "/file2.php";
To answer your question: to include the file warlock.php
that is in your included file's upper directory, this is the best solution:
要回答您的问题:要包含warlock.php
包含文件的上层目录中的文件,这是最佳解决方案:
<?php
include __DIR__ . "/../warlock.php";