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
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, , - , , !