PHP / Reference / include(), include_once(), require(), require_once()
여러 파일에 공통적으로 사용하는 코드는 별도의 파일로 만든 후 각 파일에서 불러오는 것이 좋습니다. 코드의 양이 줄어들고, 수정이 용이하기 때문입니다.
외부 파일을 포함하는 함수는 네 가지가 있습니다.
- include()
같은 파일 여러 번 포함 가능 / 포함할 파일이 없어도 다음 코드 실행 - include_once()
같은 파일 한 번만 포함 / 포함할 파일이 없어도 다음 코드 실행 - require()
같은 파일 여러 번 포함 가능 / 포함할 파일이 없으면 다음 코드 실행하지 않음 - require_once()
같은 파일 한 번만 포함 / 포함할 파일이 없으면 다음 코드 실행하지 않음
가정
a.php가 다음과 같다고 가정하겠습니다.
<h1>Lorem Ipsum Dolor</h1>
include()
예제 1
a.php 파일을 한 번 포함합니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>PHP</title>
</head>
<body>
<?php
include 'a.php';
?>
<h1>THE END</h1>
</body>
</html>

예제 2
a.php 파일을 여러 번 포함합니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>PHP</title>
</head>
<body>
<?php
include 'a.php';
include 'a.php';
?>
<h1>THE END</h1>
</body>
</html>

예제 3
포함할 파일이 없어도 그 다음 코드를 실행합니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>PHP</title>
</head>
<body>
<?php
include 'c.php';
?>
<h1>THE END</h1>
</body>
</html>

include_once()
예제 1
include_once로 같은 파일을 여러 번 포함해도 한 번만 반영됩니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>PHP</title>
</head>
<body>
<?php
include_once 'a.php';
include_once 'a.php';
?>
<h1>THE END</h1>
</body>
</html>
예제 2
include_once는 include로 포함하는 것에는 영향을 미치지 않습니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>PHP</title>
</head>
<body>
<?php
include_once 'a.php';
include 'a.php';
?>
<h1>THE END</h1>
</body>
</html>

예제 3
포함할 파일이 없어도 다음 코드를 실행합니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>PHP</title>
</head>
<body>
<?php
include_once 'c.php';
?>
<h1>THE END</h1>
</body>
</html>

require()
예제 1
a.php 파일을 한 번 포함합니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>PHP</title>
</head>
<body>
<?php
require 'a.php';
?>
<h1>THE END</h1>
</body>
</html>

예제 2
a.php 파일을 여러 번 포함합니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>PHP</title>
</head>
<body>
<?php
require 'a.php';
require 'a.php';
?>
<h1>THE END</h1>
</body>
</html>

예제 3
포함할 파일이 없으면 다음 코드를 실행하지 않습니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>PHP</title>
</head>
<body>
<?php
require 'c.php';
?>
<h1>THE END</h1>
</body>
</html>

require_once()
예제 1
require_once로 같은 파일을 여러 번 포함해도 한 번만 반영됩니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>PHP</title>
</head>
<body>
<?php
require_once 'a.php';
require_once 'a.php';
?>
<h1>THE END</h1>
</body>
</html>

예제 2
require_once는 require로 포함하는 것에는 영향을 미치지 않습니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>PHP</title>
</head>
<body>
<?php
require_once 'a.php';
require 'a.php';
?>
<h1>THE END</h1>
</body>
</html>

예제 3
포함할 파일이 없으면 다음 코드를 실행하지 않습니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>PHP</title>
</head>
<body>
<?php
require_once 'c.php';
?>
<h1>THE END</h1>
</body>
</html>









