월루를 꿈꾸는 대학생

PHP 기초 - include , require 본문

Programing/PHP

PHP 기초 - include , require

하즈시 2022. 2. 14. 09:37
728x90

외부 공통으로 쓰는 파일 불러오기 가능 

html은 상단에 반복되는 header body 등 이런 반복되는 이런 거를 별도의 파일로 불러오는 방법이 없다 = 수십수백번 copy paste 해야함 이런 거 막기 위해 php는 include와 require 쓰고 있다! 

 

1) include 

- 해당 경로의 파일을 불러온다

- include에서 불러온 파일에 에러가 있어도 개의치 않고 그 밑의 코드를 실행시킴

- 단순 반복 출력문, 에러가 있어도 문제없는 파일에 주로 사용 

- include_once를 통해 중복된 코드를 한 번만 실행시켜줌 // include는 여러번 호출해도 에러 없음

 

2) require

- include와 비슷한 역할 해당 경로의 파일을 호출

- require에서 불러온 파일에 에러가 있으면 치명적이라고 판단 그 밑의 코드 실행 x

- 데이터 베이스 혹은 에러가 있으면 치명적일 때 주로 사용 

- 2번 호출하면 두 번 선언했다고 에러가 발생 

- require의 경우 require_once를 통해 한 번만 호출할 수 있도록 선언하는 것이 바람직 

 


- include와 require를 사용해 다른 php 파일을 사용 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Include</title>
</head>
<body>

<?php
    $title="home";
    
    include('inc/header.php');
    include('inc/header.php');

   
    require('inc/function.php')

?>


<!-- 다른 php에 있는 함수를 잘 사용 중 require -->
<?php
        $fruits = [
            'apple',
            "banana",
            "mango",
            'orange'
        ];

        $result= sum(10,20);
        echo $result;

        echo output($fruits);
?>


<!--php footer 부분을 include로 불러들이기 -->
<?php 
    include('inc/footer.php');
?>

 

function.php

<?php 

function sum($x,$y){
            return $x+$y;
            
        }
        echo sum(10,20);

function output($value){
            echo '<pre>';
            print_r($value);
            echo '</pre>';
        }

?>

 

footer.php

</body>
</html>

 

header.php

<?php
    //지정되어 있지 않으면 빈값으로 지정해서 에러 안 나오도록 
    if(!isset($title)){
        $title="";
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $title ;?></title>
</head>
<body>
    <h1><?= $title; ?></h1>

 

728x90

'Programing > PHP' 카테고리의 다른 글

PHP 기초 - GET , 유효성 검사 , FILTER-INPUT  (0) 2022.02.14
PHP 기초 - get , post  (0) 2022.02.14
PHP 지역 변수 , 전역 변수, 정적 변수  (0) 2022.02.10
PHP 함수  (0) 2022.02.10
PHP 배열  (0) 2022.02.10