如何使用__dir__? [英] How to use __dir__?

查看:114
本文介绍了如何使用__dir__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用__dir__.

但是,我找不到任何有关如何进行设置的好的教程.我的Dropbox中有我的htdocs.

However, I can't find any good tutorial on how to set it up. I have my htdocs in Dropbox.

它能像这样工作吗?

 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.

然后我应该键入:

 include'__DIR__/warlock.php'; 

还是我必须输入类似的内容?

Or do I have to type something like this?

 include '___DIR__/wow/newb/guidesfornabz/classes/casters/warlock.php'; 

推荐答案

您可以使用__DIR__来获取当前脚本的目录.它仅从5.3版开始才在PHP中使用,它与使用dirname(__FILE__)相同.在大多数情况下,它用于从包含的文件中包含另一个文件.

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.

请考虑在名为inc的目录中有两个文件,该目录是我们项目目录的子文件夹,该目录位于index.php文件所在的位置.

Consider having two files in a directory called inc, which is a subfolder of our project's directory, where the index.php file lies.

project
├── inc
│   ├── file1.php
│   └── file2.php
└── index.php

如果我们从index.php开始执行include "inc/file1.php";,它将起作用.但是,从file1.php到包含file2.php,我们必须相对于index.php 做一个包含,而不是从file1.php(因此,include "inc/file2.php";)开始. __DIR__可以解决此问题,因此在file1.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.php and not from file1.php (so, include "inc/file2.php";). __DIR__ fixes this, so from file1.php we can do this:

<?php
include __DIR__ . "/file2.php";

要回答您的问题:要在包含文件的上层目录中包含文件warlock.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:

<?php
include __DIR__ . "/../warlock.php";

这篇关于如何使用__dir__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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