HOWTO · PHP

Require_once 대 PHP에 포함

이 튜토리얼에서는 PHP 파일 내에서 require, include, require_once 및 include_once를 사용하는 방법과 시기를 자세히 설명합니다.

이 페이지의 내용

개발자의 경우 개발 주기 동안 개발 또는 프로덕션 디렉토리에서 서로 다른 PHP 파일을 분리하지만 다른 PHP 파일에 함수나 클래스가 필요할 수 있습니다. 다른 파일에서 동일한 클래스나 기능을 반복하는 것은 직관적이지 않고 DRY 접근 방식에 반대됩니다.

따라서 PHP에는 include, require, include_once 및 require_once의 네 가지 키워드를 사용하여 다른 PHP 파일의 내용을 추가하거나 액세스할 수 있습니다. 이 기사에서는 모든 키워드를 고려할 것이지만 require_once 및 include에 더 집중할 것입니다.

PHP에서 include 대 require 키워드를 사용하는 경우

include 및 require 키워드는 지정된 PHP 파일의 모든 콘텐츠, 텍스트, 코드 또는 마크업을 포함 문의 대상 PHP 파일로 복사합니다. 그러나 include 키워드는 실패 처리에서 require와 다르게 작동합니다.

  • require는 치명적인 오류 (E_COMPILE ERROR)를 생성하고 스크립트를 중지합니다.
  • include는 경고 (E_WARNING)만 생성하고 다음 섹션에 포함된 PHP 파일의 코드가 필요한 경우에도 스크립트는 계속됩니다.

오류가 발생하지 않으면 두 키워드 모두 동일한 방식입니다.

현재 PHP 파일에 몇 가지 변수를 포함하는 간단한 PHP 파일(variables.php)을 추가해 보겠습니다.

variables.php 파일:

<?php

$team = 'Golden State Warriors';
$fav_player = 'Steph Curry';

?>

이제 include 키워드를 사용하여 variables.php의 내용을 추가해 보겠습니다.

<?php

echo "My favourite player is $fav_player and he plays for $team";

include 'variables.php';

echo "My favourite player is $fav_player and he plays for $team";

?>

위 코드 조각의 출력:

My favourite player is and he plays for

My favourite player is Steph Curry and he plays for Golden State Warriors

보시다시피 첫 번째 줄은 variables.php 파일을 포함하지 않았기 때문에 변수의 내용을 출력하지 않지만 일단 추가하면 변수의 내용이 있습니다.

이제 require 키워드를 사용해 보겠습니다.

<?php

echo "My favourite player is $fav_player and he plays for $team";

include 'variables.php';

echo "My favourite player is $fav_player and he plays for $team";

?>

출력:

My favourite player is and he plays for

My favourite player is Steph Curry and he plays for Golden State Warriors

동일한 출력이 생성되었습니다. 이제 코드에서 variables.php 파일의 철자를 틀리고 그 효과를 살펴보겠습니다.

include 키워드의 경우:

My favourite player is and he plays for

Warning: include(variable.php): failed to open stream: No such file or directory in /home/runner/Jinku/index.php on line 5

Warning: include(): Failed opening 'variable.php' for inclusion (include_path='.:/nix/store/bq7pj5lz7rq92p3d3qyy25lpzic9phy5-php-7.4.21/lib/php') in /home/runner/Jinku/index.php on line 5

My favourite player is and he plays for

require 키워드의 경우:

My favourite player is and he plays for

Warning: require(variable.php): failed to open stream: No such file or directory in /home/runner/Jinku/index.php on line 5

Fatal error: require(): Failed opening required 'variable.php' (include_path='.:/nix/store/bq7pj5lz7rq92p3d3qyy25lpzic9phy5-php-7.4.21/lib/php') in /home/runner/Jinku/index.php on line 5

이제 둘의 차이점을 볼 수 있습니다. include 키워드를 사용하면 포함된 파일이 없고 경고만 표시했는데도 코드가 계속 실행되었습니다.

그러나 require 키워드를 사용하면 코드에서 치명적인 오류가 발생하고 해당 지점에서 완전히 중지되었습니다.

PHP에서 require_once 대 include 키워드를 사용하는 경우

include 또는 require를 사용하는 적절한 영역이 있습니다. 항상 require를 사용하는 것이 좋습니다. 그러나 현재 PHP 파일에 추가하려는 PHP 파일의 내용 없이 애플리케이션이 수행할 수 있는 경우 문제가 없을 수 있습니다.

include, require 및 require_once 키워드를 이해하기 위해 더 많은 컨텍스트를 제공하기 위해 예를 들어보겠습니다. 이 예에서는 차이점을 보여주기 위해 포함될 functions.php 파일을 생성합니다.

functions.php 파일:

<?php

function add_sums($a, $b) {
  return $a + $b;
}

?>

포함을 사용합시다:

<html>
  <head>
    <title>PHP Test</title>
  </head>
  <body>
    <?php
    include 'functions.php';

        echo "The program is starting\n";
    $sum = add_sums(2,3);

    echo "The program is done\n";
    echo $sum;
    ?>
  </body>
</html>

코드 조각의 출력:

The program is done 5

require를 사용합시다:

<html>
  <head>
    <title>PHP Test</title>
  </head>
  <body>
    <?php
    require 'functions.php';

        echo "The program is starting\n";
    $sum = add_sums(2,3);

    echo "The program is done\n";
    echo $sum;
    ?>
  </body>
</html>

코드 조각의 출력:

The program is done 5

그러나 functions.php 파일을 사용할 수 없고 include를 사용하면 다음이 출력됩니다.

Warning: include(functions.php): failed to open stream: No such file or directory in /home/runner/Jinku/index.php on line 7

Warning: include(): Failed opening 'functions.php' for inclusion (include_path='.:/nix/store/bq7pj5lz7rq92p3d3qyy25lpzic9phy5-php-7.4.21/lib/php') in /home/runner/Jinku/index.php on line 7

The program is starting

Fatal error: Uncaught Error: Call to undefined function add_sums() in /home/runner/Jinku/index.php:9 Stack trace: #0 {main} thrown in /home/runner/Jinku/index.php on line 9

functions.php는 없었지만 정의되지 않은 함수에 대한 호출로 인해 치명적인 오류가 발생할 때까지 코드는 여전히 실행 중이었습니다. 이는 PHP 애플리케이션 내에서 작동하는 효과적인 수단이 아닙니다.

그러나 require를 사용할 때 오류는 다음과 같습니다.

Warning: require(functions.php): failed to open stream: No such file or directory in /home/runner/Jinku/index.php on line 7

Fatal error: require(): Failed opening required 'functions.php' (include_path='.:/nix/store/bq7pj5lz7rq92p3d3qyy25lpzic9phy5-php-7.4.21/lib/php') in /home/runner/Jinku/index.php on line 7

require 키워드를 사용했기 때문에 정의되지 않은 함수 호출로 인한 치명적인 오류를 방지할 수 있었습니다. 다소 복잡한 PHP 애플리케이션의 경우 require가 오류를 빠르게 포착하고 원치 않는 결과를 방지하는 데 더 적합합니다.

이제 한 단계 더 나아가 보겠습니다. require_once 키워드를 사용해 보겠습니다.

<html>
  <head>
    <title>PHP Test</title>
  </head>
  <body>
    <?php
        // Previous code START
    require_once 'functions.php';

        echo "The program is starting\n";
    $sum = add_sums(2,3);

    echo "The program is done\n";
    echo $sum;
        // Previous code ENDS

        // Additional code STARTS

    echo "Another program begins";
    require 'functions.php';
    $sum = add_sums(2,3);
    echo $sum;
    echo "Another program ends";
    ?>
  </body>
</html>

위 코드 조각의 출력은 치명적인 오류를 생성합니다.

The program is starting
The program is done
5
Another program begins

Fatal error: Cannot redeclare add_sums() (previously declared in /home/runner/Jinku/functions.php:3) in /home/runner/Jinku/functions.php on line 3

require_once 키워드는 파일이 포함되었는지 확인하고 포함되어 있으면 포함하지 않거나 다시 요구합니다. 따라서 이전에 require_once 키워드를 사용했기 때문에 functions.php의 코드를 요구하거나 포함하는 것을 방지합니다.

코드에 비용이 많이 들 수 있는 함수 호출의 재선언 또는 변수 값 할당을 방지하기 위해 이 작업을 수행할 수 있습니다.

예에서 require를 두 번 사용하면 함수를 다시 호출하고 이전과 동일한 효과를 생성하므로 값이 5가 됩니다.

조합 이해하기:

  • require 및 require_once는 치명적인 오류를 발생시킵니다.
  • include 및 include_once는 치명적인 오류를 발생시킵니다.
  • require_once 및 require_once는 제대로 작동하지만 모든 콘텐츠가 회수되고 다시 선언됩니다.
  • include_once 및 include_once는 제대로 작동하지만 모든 콘텐츠가 회수되고 다시 선언됩니다.