为什么有些框架使用更长的包含语法?
Why do some frameworks use a longer include syntax?
似乎以下两种代码风格做同样的工作:
require_once './foo.php';
require_once './../bar.php';
require_once __DIR__.'/foo.php';
require_once __DIR__.'/../bar.php';
显然,第一种形式更短更简洁。但是,我在很多第三方代码中看到了第二种形式。有什么理由更喜欢第二种形式吗?
例如,__DIR__
是 magic constant, relative to the current script's file. The dot .
, however, is relative to the current working directory, that could have been altered by chdir()
。
来自PHP.NET:
__DIR__
The directory of the file. If used inside an include, the directory of
the included file is returned. This is equivalent to
dirname(__FILE__)
. This directory name does not have a trailing
slash unless it is the root directory.
然后在评论中解决您的问题:
A lot of notes here concern defining the __DIR__
magic constant for
PHP versions not supporting the feature. Of course you can define this
magic constant for PHP versions not yet having this constant, but it
will defeat its purpose as soon as you are using the constant in an
included file, which may be in a different directory then the file
defining the __DIR__
constant. As such, the constant has lost its
magic, and would be rather useless unless you assure yourself to have all of your includes in the same directory.
似乎以下两种代码风格做同样的工作:
require_once './foo.php';
require_once './../bar.php';
require_once __DIR__.'/foo.php';
require_once __DIR__.'/../bar.php';
显然,第一种形式更短更简洁。但是,我在很多第三方代码中看到了第二种形式。有什么理由更喜欢第二种形式吗?
__DIR__
是 magic constant, relative to the current script's file. The dot .
, however, is relative to the current working directory, that could have been altered by chdir()
。
来自PHP.NET:
__DIR__
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to
dirname(__FILE__)
. This directory name does not have a trailing slash unless it is the root directory.
然后在评论中解决您的问题:
A lot of notes here concern defining the
__DIR__
magic constant for PHP versions not supporting the feature. Of course you can define this magic constant for PHP versions not yet having this constant, but it will defeat its purpose as soon as you are using the constant in an included file, which may be in a different directory then the file defining the__DIR__
constant. As such, the constant has lost its magic, and would be rather useless unless you assure yourself to have all of your includes in the same directory.