为什么在require_once中包含__DIR__? [英] Why include __DIR__ in the require_once?

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

问题描述

例如,我总是看到这样的自动加载器:

For example, I always see autoloaders called like this:

require_once __DIR__ . '/../vendor/autoload.php';

那和更简洁的有什么区别

What is the difference between that and the more concise

require_once '../vendor/autoload.php';

?

推荐答案

PHP脚本相对于当前路径(getcwd()的结果)运行,而不是相对于其自己文件的路径运行.使用__DIR__会强制包含相对于其自己的路径发生.

PHP scripts run relative to the current path (result of getcwd()), not to the path of their own file. Using __DIR__ forces the include to happen relative to their own path.

为演示,创建以下文件(和目录):

To demonstrate, create the following files (and directories):

- file1.php
- dir/
   - file2.php
   - file3.php

如果file2.php这样包含file3.php:

include `file3.php`.

如果直接调用file2.php,它将正常工作.但是,如果file1.php 包括 file2.php,则当前目录(getcwd())对于file2.php将是错误的,因此不能包含file3.php.

It will work fine if you call file2.php directly. However, if file1.php includes file2.php, the current directory (getcwd()), will be wrong for file2.php, so file3.php cannot be included.

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

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