PHP 문서에서 다른 문서 불러오기

php 문서에서 다른 문서(ex. 공통문서)를 불러와본다.

include

  • 특정 조건일 때 지정한 파일이 삽입되도록 처리 가능하다.
  • 삽입 실패시(파일 및 문서가 존재하지 않을 경우) 존재하지 않는다는 문구를 출력하고 계속 파싱한다.
  • 여러 번 출력하고 싶을 경우도 가능하다. (include 여러 번 사용 가능)

/common/header.php

1
2
3
4
5
6
7
8
<!DOCTYPE html>
<html lang="ko">
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scal=1.0">
<title><?= $title; ?></title> // 변수명 출력
</head>

index.php

1
2
3
4
5
6
7
8
9
10
<?php
// 변수 선언 전에 include 먼저 선언되거나
// 선언 자체가 되지 않을 경우 에러 발생
$title = 'home';
include('common/header.php');
?>
<body>
……내용……
</body>
</html>

결과

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="ko">
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scal=1.0">
<title>home</title> // 변수명 출력
</head>
<body>
……내용……
</body>
</html>

안전하게 진행하고 싶을 경우 변수 선언이 되지 않았을 때 빈값을 삽입하도록 하단과 같이 /common/header.php에 if문을 삽입한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// !isset($title): 타이틀이 존재하지 않을 때
<?php
if(!isset($title)) {
$title = '';
}
?>
<!DOCTYPE html>
<html lang="ko">
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scal=1.0">
<title><?= $title; ?></title> // 변수명 출력
</head>

include_once

include와 동일한 기능을 하지만, 여러 번 호출을 하더라도 include와 달리 한번만 불러온다.
index.php

1
2
3
4
5
6
7
8
9
<?php
$title = 'home';
include_once('common/header.php');
include_once('common/header.php'); // 두 번 호출
?>
<body>
……내용……
</body>
</html>

결과

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="ko">
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scal=1.0">
<title>home</title> // 변수명 출력
</head>
<body>
……내용……
</body>
</html>

require

  • 파일을 무조건 삽입해야 할 때 사용해야 한다. (조건을 만족하지 않아도 파일을 삽입한다)
  • 삽입 실패시(파일 및 문서가 존재하지 않을 경우) 존재하지 않는다는 문구를 출력하고 해당 파일을 중지한다.
  • 여러 번 호출할 경우 여러번 선언되었다는 에러가 발생한다.

/common/functions.php

1
2
3
4
5
function increment() {
static $count = 0; //정적 변수
echo "{$count}";
$count++;
}

index.php

1
2
3
4
5
6
7
8
9
<?php
require('common/functions.php');
?>

<?php
increment(); // 0
increment(); // 1
increment(); // 2
?>

require_once

여러 번 호출되더라도 한 번만 호출한다.

index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
// 오류 발생
require('common/functions.php');
require('common/functions.php');

// 오류 미발생
require_once('common/functions.php');
require_once('common/functions.php');
?>

<?php
increment(); // 0
increment(); // 1
increment(); // 2
?>

REFERENCE
https://www.youtube.com/watch?v=rCDuvv4ZZE8&list=PL-qMANrofLytZY15Agdi7wFc1seGO7Onb&index=5

  • © 2020-2025 404 Not Found
  • Powered by Hexo Theme Ayer