代码之家  ›  专栏  ›  技术社区  ›  Urda Gael Fraiteur

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

  •  23
  • Urda Gael Fraiteur  · 技术社区  · 16 年前

    getcwd()
    dirname(__FILE__)
    

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

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

    返回:

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

    3 回复  |  直到 13 年前
        1
  •  52
  •   user664833 Ronen Rabinovici    8 年前

    __FILE__ 是一个 magic constant 包含您正在执行的文件的完整路径。如果您在include中,则其路径将是 __文件__

    因此,通过这种设置:

    /文件夹/random/foo.php

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

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

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

    getcwd() 返回开始执行的目录,而 dirname(__FILE__) 依赖于文件。

    在我的网络服务器上, pwd . 这一点得到了 documentation of the CLI SAPI getcwd 手册页:

    就像:

    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

    更新 :由于PHP5.3.0,您还可以使用magic常量 __DIR__ 这相当于 目录名(文件名)

        2
  •  1
  •   Daniel A. White    16 年前

    试试这个。

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

    这应该是结果。

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

    我想 getcwd 用于文件操作,其中 dirname(__FILE__) 使用魔法常数 __FILE__


    编辑:我错了。

    chdir .

    所以如果你这么做。。。

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

        3
  •  1
  •   commonpike    10 年前

    cd foo
    php bin/test.php
    

    在test.php中, getcwd() 会回来吗 foo (您当前的工作目录)和 dirname(__FILE__) bin