youngfromnowhere
[PHP] include의 특성 본문
include문이 포함된 파일을 include할 때
예상하지 못한 특성이 발견되어 기록한다.
test를 위해 다음과 같이 directory를 구성한다.

index.php가 a.php를 include하고
a.php가 b.php를 include하도록 만든다.
각 파일의 내용은 다음과 같다.
#index.php
<?php
include "subdir_1/a.php";
echo "\$a_var : ".$a_var."\n";
echo "\$b_var : ".$b_var."\n";
?>
#subdir_1/a.php
<?php
include "../subdir_2/b.php";
$a_var = "this is \$a_var";
?>
#subdir_2/b.php
<?php
$b_var = "this is \$b_var";
?>
a.php에 대하여 b.php의 상대경로는 ../subdir_2/b.php가 맞으므로, 문제가 없어보인다.
이제 index.php를 실행시키면..

../subdir_2/b.php를 찾을 수 없다는 에러 메세지가 뜬다.
a.php를 다음과 같이 수정한다.
#subdir_1/a.php Modified
<?php
include "subdir_2/b.php";
$a_var = "this is \$a_var";
?>
그러면 의도한대로 작동한다.

즉, a.php에 포함되어 있던 include 문에 인자로 들어간 path는, a.php를 기준으로한 상대경로가 아니라, a.php를 include한 index.php 파일을 기준으로 한 상대경로여야 한다.
그 말은, include문이 다중으로 겹쳐있을(nested) 경우 언제나 '최상위 코드'가 실행되는 파일을 기준으로 path를 줘야 한다는 것이다. 문제는, 복잡한 directory 구조와 file간의 dependency를 가진 프로그램일 경우, 최초로 include 문이 실행된 파일이 무엇인지 알기 어렵다는 것이다.
이 문제를 해결하기 위해서는, '현재 파일이 포함된 directory의 경로'를 반환하는 __DIR__라는 상수를 사용하는 것이 좋다. (https://www.php.net/manual/en/language.constants.magic.php)
__DIR__를 이용하여 위 파일들을 수정하자.
#index.php
<?php
include __DIR__."/subdir_1/a.php";
echo "\$a_var : ".$a_var."\n";
echo "\$b_var : ".$b_var."\n";
?>
#subdir_1/a.php
<?php
include __DIR__."/../subdir_2/b.php";
$a_var = "this is \$a_var";
?>
__DIR__ 뒤에 상대경로를 연산자 "."를 이용하여 붙여준다. (__DIR__ 의 반환값은 끝에 slash가 없으므로 따로 붙여주어야 한다.)

이제 a.php에서 b.php를 바라볼 때의 상대경로를 써줄 수 있다.
'PHP&Apache2 > PHP' 카테고리의 다른 글
| [PHP] 외부 data를 superglobal 없이 바로 받을 수 있었던 이유. (0) | 2023.08.10 |
|---|---|
| [PHP] HTTP GET, POST로 전달받은 data들 (미해결) (0) | 2023.07.21 |
| [PHP] php & operator : reference 연산자 (0) | 2023.06.26 |