Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Directory getcwd()和dirname(_文件__)之间的差异?我应该用哪一种?_Directory_Php - Fatal编程技术网

Directory getcwd()和dirname(_文件__)之间的差异?我应该用哪一种?

Directory getcwd()和dirname(_文件__)之间的差异?我应该用哪一种?,directory,php,Directory,Php,在PHP中,两者之间的区别是什么 getcwd() dirname(__FILE__) 当我从CLI回显时,它们都返回相同的结果 echo getcwd()."\n"; echo dirname(__FILE__)."\n"; 返回: /home/user/Desktop/testing/ /home/user/Desktop/testing/ 哪一个最好用?这有关系吗?更高级的PHP开发人员喜欢什么?试试这个 将文件移动到另一个目录,例如testing2 这应该是结果 /home/use

在PHP中,两者之间的区别是什么

getcwd()
dirname(__FILE__)
当我从CLI回显时,它们都返回相同的结果

echo getcwd()."\n";
echo dirname(__FILE__)."\n";
返回:

/home/user/Desktop/testing/
/home/user/Desktop/testing/
哪一个最好用?这有关系吗?更高级的PHP开发人员喜欢什么?

试试这个

将文件移动到另一个目录,例如
testing2

这应该是结果

/home/user/Desktop/testing/
/home/user/Desktop/testing/testing2/
我认为
getcwd
用于文件操作,其中
dirname(\uuuuu file\uuuu)
使用魔法常量
\uuu file\uuuuu
并使用实际的文件路径


编辑:我错了

您可以使用
chdir
更改工作目录

所以如果你这么做

chdir('something');
echo getcwd()."\n";
echo dirname(__FILE__)."\n";

这些应该是不同的。

\uuuu文件\uuuuu
是一个包含您正在执行的文件的完整路径的文件。如果您在一个include中,它的路径将是
\uu文件的内容

因此,通过这种设置:

/folder/random/foo.php

因此
getcwd()
返回您开始执行的目录,而
dirname(\uuuu FILE\uuu)
依赖于文件

在我的Web服务器上,
getcwd()
返回最初开始执行的文件的位置。使用CLI,它与执行
pwd
时得到的结果相同。这得到了手册页面上的和注释的支持:

与其他SAPI不同,CLI SAPI不会自动将当前工作目录更改为启动脚本所在的目录

就像:

thom@griffin/home/thom$echo”“>>test.php
thom@griffin/home/thom$php test.php
/家庭/托姆
thom@griffin/home/thom$cd。。
thom@griffin/home$php thom/test.php
/家
当然,另请参见


更新:由于PHP5.3.0,您还可以使用神奇常数
\uuuu DIR\uuuuu
,它相当于
dirname(\uuu FILE\uuuuu)
,如果您从命令行调用该文件,区别是显而易见的

cd foo
php bin/test.php

在test.php中,
getcwd()
将返回
foo
(您当前的工作目录)和
dirname(\uuuuu文件)
将返回
bin
(正在执行的文件的dirname)。

不,这次它只是回显/home/user/Desktop/testing/testing2 twiceOK,所以让我确定我得到了这个。。。dirname(FILE)将始终生成正在使用的文件的位置。而getcwd将返回运行的PHP进程的当前工作目录(比如我的命令行脚本),因此假设我使用include(“path/to/some/file/from/chdir/”;它应该能够找到参考文件?完美的例子是完美的!非常感谢。是否有一种快速方法可以从包含的脚本中获取主脚本的目录。因此,在一个包含在不同目录中的脚本中,我想知道包含它的主脚本的目录。@CMCDRANGKAI:我不知道是否有更好的方法,但您可以尝试将主文件中的常量设置为
\uu DIR\uu
@ThomWiggers,似乎
\uuuuu DIR\uuuuuuu
的性能更好,是吗?我不知道它们内部是如何工作的,所以我不知道。不过,我怀疑这有多重要,您可能应该根据功能做出选择。别忘了
dirname(\uuuuu FILE\uuuu)
\uu DIR\uuuuu
<?php
echo getcwd() . "\n";
echo dirname(__FILE__) . "\n";
thom@griffin /home/thom $ echo "<?php echo getcwd() . '\n' ?>" >> test.php
thom@griffin /home/thom $ php test.php 
/home/thom
thom@griffin /home/thom $ cd ..
thom@griffin /home $ php thom/test.php 
/home
cd foo
php bin/test.php