getcwd 和 __DIR__ 有什么区别?
What is the difference betweed getcwd and __DIR__?
DIR 是 PHP docs. getcwd() is just the current working directory according to the PHP docs.
中所述的神奇常量
我的用例是:
// this is my index.php file
require_once __DIR__ . '/vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
$app->get('/{name}', function($name) use($app) {
return $app->sendFile(__DIR__ . '/web/source/index.php');
});
我不完全理解为什么我需要这些机制中的任何一个,因为我应该能够使用相对路径。
但是代码没有它就失败了。
假设您有脚本
<?php
echo __DIR__, ' | ', getcwd();
include 'subdir/foo.php';
它作为主脚本执行(由于浏览器请求或者它是 php-cli 调用的主脚本)。
和 subdir/foo.php
除了 include
.
是一样的
主脚本的输出可能类似于
/path | /path
但是 subdir/foo.php
包含在主脚本中时的输出将是
/path/subdir | /path
__DIR__反映了当前脚本文件所在的目录。
但是 include() 没有改变当前工作目录,所以 getcwd() 的输出仍然是 /path
.
__DIR__
是当前正在执行的文件所在的位置。
getcwd()
是当前目录 php 文件正在执行。请记住,您在服务器上而不是客户端上,需要注意您正在使用的目录。
这可以改变。
有关此概念的更多信息,请参阅 here。
DIR 是 PHP docs. getcwd() is just the current working directory according to the PHP docs.
中所述的神奇常量我的用例是:
// this is my index.php file
require_once __DIR__ . '/vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
$app->get('/{name}', function($name) use($app) {
return $app->sendFile(__DIR__ . '/web/source/index.php');
});
我不完全理解为什么我需要这些机制中的任何一个,因为我应该能够使用相对路径。
但是代码没有它就失败了。
假设您有脚本
<?php
echo __DIR__, ' | ', getcwd();
include 'subdir/foo.php';
它作为主脚本执行(由于浏览器请求或者它是 php-cli 调用的主脚本)。
和 subdir/foo.php
除了 include
.
主脚本的输出可能类似于
/path | /path
但是 subdir/foo.php
包含在主脚本中时的输出将是
/path/subdir | /path
__DIR__反映了当前脚本文件所在的目录。
但是 include() 没有改变当前工作目录,所以 getcwd() 的输出仍然是 /path
.
__DIR__
是当前正在执行的文件所在的位置。
getcwd()
是当前目录 php 文件正在执行。请记住,您在服务器上而不是客户端上,需要注意您正在使用的目录。
这可以改变。
有关此概念的更多信息,请参阅 here。