问题
DIR is a magic constant as stated in the PHP docs. getcwd() is just the current working directory according to the PHP docs.
My use case is:
// this is my index.php file
require_once __DIR__ . '/vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
$app->get('/{name}', function($name) use($app) {
return $app->sendFile(__DIR__ . '/web/source/index.php');
});
I don't fully understand why I need either of these mechanisms as I should just be able to use relative paths.
However the code fails with out it.
回答1:
__DIR__
is where the currently executing file is.
getcwd()
is the current directory php file is executing from. Remember you are on the server and not the client and need to be mindful of what directory you are working from.
This can change.
See here for more on this concept.
回答2:
Let's assume you have the script
<?php
echo __DIR__, ' | ', getcwd();
include 'subdir/foo.php';
and it gets executed as the main script (because of a browser request or it's the main script for php-cli call).
And subdir/foo.php
is the same except for the include
.
The output for the main script might be something like
/path | /path
but the output for subdir/foo.php
when included by the main script will be
/path/subdir | /path
__DIR__ reflects the directory in which the current script file resides.
But include() didn't change the current working directory, so the output of getcwd() remains /path
.
来源:https://stackoverflow.com/questions/31407994/what-is-the-difference-betweed-getcwd-and-dir