Absolute vs. relative paths

后端 未结 5 828
温柔的废话
温柔的废话 2020-11-30 03:02

If I use absolute paths, I can\'t move the whole directory to a new location. If I use relative paths, I can\'t move individual files to new locations.

What\'s the s

5条回答
  •  执念已碎
    2020-11-30 03:05

    I've seen in some projects that people use dirname(FILE). What is the point of that, I mean, why not simply leave it out since the dirname is relative anyway (depending on where the file sits)?

    It's relative to the include path, anyway. The dirname( __FILE__ ) (or just __DIR__ in PHP >= 5.3) is there so you can run the file from every location. In case you're using relative paths, the value "." may change. See:

    berry@berry-pc:~% cat so.php

    berry@berry-pc:~% php so.php

    string(11) "/home/berry"
    string(11) "/home/berry"
    

    berry@berry-pc:~% cd foo

    berry@berry-pc:~/foo% php ../so.php

    string(15) "/home/berry/foo"
    string(11) "/home/berry"
    

    So, it is relative, but it's relative to the current working directory, not to the directory the file is located in. That's why you'll want to use __DIR__ for this. And by the way; yes, I don't move files around an awful lot. If I do though, I'll have to update every call to that file, although I don't require or include an awful lot anymore, since I'm using an Autoloader.

    As for the other files I'm referring to (such as template files), I set the path manually, but once. I then refer to $path . '/filename.php';, so it's easier to change later.

提交回复
热议问题