getcwd()和dirname(__ FILE__)之间的区别?我应该使用哪个?

问题描述 投票:23回答:3

在PHP中有什么区别

getcwd()
dirname(__FILE__)

当我从CLI回显时,它们都返回相同的结果

echo getcwd()."\n";
echo dirname(__FILE__)."\n";

返回:

/home/user/Desktop/testing/
/home/user/Desktop/testing/

哪个是最好用的?有关系吗?更高级的PHP开发人员更喜欢什么?

directory php
3个回答
49
投票

__FILE__是一个magic constant,包含您正在执行的文件的完整路径。如果你在include中,它的路径将是__FILE__的内容。

所以使用此设置:

/folder/random/foo.PHP

<?php
echo getcwd() . "\n";
echo dirname(__FILE__) . "\n" ;
echo "-------\n";
include 'bar/bar.php';

/folder/random/把人/把人.PHP

<?php
echo getcwd() . "\n";
echo dirname(__FILE__) . "\n";

你得到这个输出:

/folder/random
/folder/random
-------
/folder/random
/folder/random/bar

所以getcwd()返回你开始执行的目录,而dirname(__FILE__)是文件相关的。

在我的网络服务器上,getcwd()返回最初开始执行的文件的位置。使用CLI它等于执行pwd时的结果。这得到了documentation of the CLI SAPI的支持以及对getcwd手册页的评论:

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

所以喜欢:

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

当然,请参阅http://php.net/manual/en/function.getcwd.php上的手册

更新:从PHP 5.3.0开始,你也可以使用相当于__DIR__的魔法常量dirname(__FILE__)


1
投票

试试这个。

将您的文件移动到另一个目录testing2

这应该是结果。

/home/user/Desktop/testing/
/home/user/Desktop/testing/testing2/

我认为getcwd用于文件操作,其中dirname(__FILE__)使用魔法常量__FILE__并使用实际的文件路径。


编辑:我错了。

那你可以用chdir改变工作目录。

所以,如果你那样做......

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

那些应该是不同的。


1
投票

如果从命令行调用该文件,则差异很明显。

cd foo
php bin/test.php

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

© www.soinside.com 2019 - 2024. All rights reserved.