getcwd() 和 dirname(__FILE__) 之间的区别?我应该使用哪个?
PHP 中的区别是什么
getcwd()目录名(__文件__)
当我从 CLI 回显时,它们都返回相同的结果
echo getcwd()."
";echo 目录名(__FILE__)."
";
返回:
/home/user/Desktop/testing//家/用户/桌面/测试/
哪个最好用?有关系吗?更高级的 PHP 开发人员更喜欢什么?
解决方案__FILE__
是一个 魔法常量 包含您正在执行的文件的完整路径.如果你在一个包含中,它的路径将是 __FILE__
的内容.
所以有了这个设置:
/folder/random/foo.php
/folder/random/bar/bar.php
你得到这个输出:
/folder/random/文件夹/随机-------/文件夹/随机/文件夹/随机/条
所以 getcwd()
返回你开始执行的目录,而 dirname(__FILE__)
是文件相关的.
在我的网络服务器上,getcwd()
返回最初开始执行的文件的位置.使用 CLI,它与执行 pwd
时得到的结果相同.这由 CLI SAPI 文档 和评论支持在 getcwd
手册页上:
CLI SAPI 确实 - 与其他 SAPI 不同 - 不会自动将当前工作目录更改为启动脚本所在的目录.
所以喜欢:
thom@griffin/home/thom $ echo "<?php echo getcwd() . '
' ?>">>测试.phpthom@griffin/home/thom $ php test.php/家/汤姆thom@griffin/home/thom $ cd ..汤姆@格里芬/home $ php 汤姆/test.php/家
当然,也请参见http://php.net/manual/en/function.getcwd.php
UPDATE:自 PHP 5.3.0 起,您还可以使用魔术常量 __DIR__
,它等效于 dirname(__FILE__)
.>
In PHP what is the difference between
getcwd()
dirname(__FILE__)
They both return the same result when I echo from CLI
echo getcwd()."
";
echo dirname(__FILE__)."
";
Returns:
/home/user/Desktop/testing/
/home/user/Desktop/testing/
Which is the best one to use? Does it matter? What to the more advanced PHP developers prefer?
解决方案__FILE__
is a magic constant containing the full path to the file you are executing. If you are inside an include, its path will be the contents of __FILE__
.
So with this setup:
/folder/random/foo.php
<?php
echo getcwd() . "
";
echo dirname(__FILE__) . "
" ;
echo "-------
";
include 'bar/bar.php';
/folder/random/bar/bar.php
<?php
echo getcwd() . "
";
echo dirname(__FILE__) . "
";
You get this output:
/folder/random
/folder/random
-------
/folder/random
/folder/random/bar
So getcwd()
returns the directory where you started executing, while dirname(__FILE__)
is file-dependent.
On my webserver, getcwd()
returns the location of the file that originally started executing. Using the CLI it is equal to what you would get if you executed pwd
. This is supported by the documentation of the CLI SAPI and a comment on the getcwd
manual page:
the CLI SAPI does - contrary to other SAPIs - NOT automatically change the current working directory to the one the started script resides in.
So like:
thom@griffin /home/thom $ echo "<?php echo getcwd() . '
' ?>" >> test.php
thom@griffin /home/thom $ php test.php
/home/thom
thom@griffin /home/thom $ cd ..
thom@griffin /home $ php thom/test.php
/home
Of course, see also the manual at http://php.net/manual/en/function.getcwd.php
UPDATE: Since PHP 5.3.0 you can also use the magic constant __DIR__
which is equivalent to dirname(__FILE__)
.
相关文章