Rob*_*cks 39 php url relative-path include
A.这是做什么的?
require ("./file.php");
Run Code Online (Sandbox Code Playgroud)
B.与此相比?
require ("file.php");
Run Code Online (Sandbox Code Playgroud)
(它不是一个目录..这将是)
require ("../file.php");
Run Code Online (Sandbox Code Playgroud)
第一个版本强制内部机制相对于...直接执行的文件包含文件.例如,你有
的index.php
// directly executed script (php -f index.php or from a browser)
include 'second.php';
Run Code Online (Sandbox Code Playgroud)
second.php
// This is included relatively to index.php
// Actually, it is first searched relatively to include_path, then relatively
// to index.php
include './third.php';
Run Code Online (Sandbox Code Playgroud)
third.php
// This is included relatively to second.php ONLY. It does not search
// include_path
return "foo";
Run Code Online (Sandbox Code Playgroud)
简答
你是对的,它不是一个目录.一个 .指的是您所在的目录,而..指的是父目录.
含义,./ file.php和file.php在PHP中功能相同.这是相关的文档页面:http: //us.php.net/manual/en/wrappers.file.php
更长的答案
然而,仅仅因为它们在这种情况下的工作方式相同并不意味着它们总是相同的.
当您在*nix shell环境中操作并键入可执行文件的名称时,shell将查找PATH目录,但它不会查找CWD或您当前所在的目录.
因此,如果您所在的目录中有一个名为myprogram.php的文件(这将是一个PHP CLI文件),您只需键入:
myprogram.php
程序是否可执行无关紧要.shell将在/ bin /,/ usr/bin/etc中查找您的文件,但它不会查找./或您所在的目录.
要在不将目录添加到PATH的情况下执行该程序,您需要键入
./myprogram
所以,真的,./更明确.这意味着,"你正在寻找的文件就在这里"而没有./意味着,"该文件应该是程序寻找文件的地方".
编辑:为了清楚起见,我已经完全重写了答案
包含文件时,您可以使用./myfile.php或myfile.php.
它们并不相同,您最好始终使用第一种语法,除非您知道自己在做什么。
通过一个示例可以最好地说明差异:假设您有以下文件和文件夹结构:
index.php
inc/inner.php
Run Code Online (Sandbox Code Playgroud)
从index.php,您可以包含不带“ ”的内部模板./,它将按预期工作:
index.php
inc/inner.php
Run Code Online (Sandbox Code Playgroud)
现在假设我们添加一个新文件,因此文件夹结构现在如下所示:
index.php
inc/inner.php
inc/inner-inner.php
Run Code Online (Sandbox Code Playgroud)
要包含inner-inner.php在 中inner.php,我们会这样做......对吗?
# index.php
<?php
include "inc/inner.php";
Run Code Online (Sandbox Code Playgroud)
错误的。只会在根文件夹inner.php中查找。inner-inner.php
index.php
* inner-inner.php <- Doesn't exist, PHP ERROR.
inc/inner.php
inc/inner-inner.php
Run Code Online (Sandbox Code Playgroud)
相反,我们应该使用./包含内部-内部的语法。这将指示我们包含的文件必须相对于当前文件包含,而不是相对于PHP 脚本的当前“入口点”(index.php在示例中)。
# src/inner.php
<?php
include "./inner-inner.php";
Run Code Online (Sandbox Code Playgroud)
此外,正如其他评论中提到的,如果您为 PHP 应用程序配置了不同的“加载路径”,则将首先查找该加载路径,而无需使用./语法。相反,./语法更有效,因为它不检查 php 1的“包含路径” 。
如果你想让你的包含更加明确,请使用__DIR__常量。这告诉 php:“使用该文件的目录” 2。
index.php
inc/inner.php
inc/inner-inner.php
Run Code Online (Sandbox Code Playgroud)
参考:
| 归档时间: |
|
| 查看次数: |
13707 次 |
| 最近记录: |