我遇到了一个有这种结构的项目。
-projectRoot
--src
---bootstrap.php
--composer.json
--public
---index.php
---css
---images
现在在公共目录中,index.php
包含以下内容
//in projectRoot/public/index.php
<?php
require __DIR__."/../src/bootstrap.php";
?>
我理解__DIR__
常量解析到当前正在执行的php脚本文件的绝对目录。所以在上面的例子中我希望它是ProjectRoot/public
。
index.php中的哪个路径require
会查看?以上路径中的父目录..
解析为什么?
PS :我读到上面设置的重点是确保相对路径继续工作,无论在哪里调用index.php。这是如何工作的?感谢。
答案 0 :(得分:4)
<?php
require __DIR__ . "/some_file.php";
/* __DIR__ SIMPLY POINTS TO THE DIRECTORY IN WHICH THE ACTIVE SCRIPT LIVES
- THE DIRECTORY OF THE EXECUTING SCRIPT... THEN REQUIRES THE FILE
"some_file.php" WITHIN THAT DIRECTORY.
THE REAL-PATH SHOULD REFLECT SOMETHING LIKE: projectRoot/public/some_file.php
*/
require __DIR__ . "/../src/bootstrap.php";
/* FOLLOWING THE LOGIC ABOVE, __DIR__ . "/../" __DIR__ AGAIN POINTS TO
THE DIRECTORY IN WHICH THE ACTIVE SCRIPT LIVES WHILE "/../" TELLS
THE REQUIRE DIRECTIVE TO LOOK ONE DIRECTORY ABOVE THE CURRENT DIRECTORY
(AND LOCATE WITHIN THAT DIRECTORY ANOTHER DIRECTORY CALLED "src" IN THIS CASE...)
THEN WITHIN THAT "scr" DIRECTORY LOOK FOR A FILE CALLED:
"bootstrap.php" AND REQUIRE/INCLUDE IT...
THE REAL-PATH SHOULD REFLECT SOMETHING LIKE: projectRoot/src/bootstrap.php
*/
// TO UNDERSTAND THESE CONCEPTS MORE CLEARLY, IT WOULD BE ADVISED TO
// TRY SOMETHING LIKE THESE:
var_dump( realpath(__DIR__ . "/../src/bootstrap.php") );
var_dump( realpath(__DIR__ . "/index.php") );
答案 1 :(得分:1)
以下是index.php
__DIR__ // This will be projectRoot/public
/../ // This will go one level up so it'll be projectRoot
src/ // This will go inside the src folder (projectRoot/src)
bootstrap.php // This will open the bootstrap.php
所以最后,它会定位projectRoot/src/bootstrap.php
...那是他们要求的文件。