Why do many PHP developers use "__DIR__." .. / otherFolder? "?

Often I see this type of code __DIR__.'/../Resources/config'. But why is this so, I am mistaken, is it the same as typing ../Resources/config'?

+4
source share
2 answers

No, this is not always the same thing. __DIR__is the file directory, not the current working directory. This code is essentially a dynamically generated absolute path.

Write this in ~/foo/script.php:

<?php
// Ta, Sven
//  https://php.net/manual/en/function.realpath.php#84012
function get_absolute_path($path) {
    $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
    $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
    $absolutes = array();
    foreach ($parts as $part) {
        if ('.' == $part) continue;
        if ('..' == $part) {
            array_pop($absolutes);
        } else {
            $absolutes[] = $part;
        }
    }
    return '/' . implode(DIRECTORY_SEPARATOR, $absolutes);
}

$p = __DIR__ . '/../bar';
echo $p . "\n" . get_absolute_path($p) . "\n";
?>

Now:

$ cd ~/foo
$ PHP .php
/home/me/foo/../bar
/home/me/bar

$ cd ~/
$ php foo/script.php
/home/me/foo/../bar
/home/me/bar

But if we got rid of __DIR__:

$ cd ~/foo
$ PHP .php
../bar
/home/me/bar

$ cd ~/
$ php foo/script.php
../bar
/home/bar

See .... the last way is wrong.

If we used these paths anywhere, they would be broken without __DIR__.

, script, , - , , !

+5

, , script . __ DIR __ , .

, ,

/
test/
test/script.php
test/Resource/config
another/

script.php , script test, test/Resource/config. , .

script, another, another/Resource/config, .

__DIR__, script, . , /test/Resource/config

, script, , .

+6

Source: https://habr.com/ru/post/1612806/


All Articles