IMG-LOGO
공지사항 :

PHP include와 namespace

lmkfox - 2025-08-01 06:29:41 26 Views 0 Comment

1. include — 외부 파일 불러오기

PHP에서 include는 다른 PHP 파일의 코드를 현재 파일로 가져오는 기능입니다. 코드 재사용, 유지보수성 향상, 구조화된 프로젝트에 필수입니다.

종류

문법

설명

include 'file.php';

파일을 불러오며, 실패 시 **경고(warning)**만 발생

require 'file.php';

실패 시 치명적 에러(fatal error) 발생

include_once 'file.php';

중복 포함 방지

require_once 'file.php';

중복 포함 방지 + 실패 시 치명적 에러

예시

파일: config.php

<?php
$site_name = "My Site";
?>

파일: index.php

<?php
include 'config.php';
echo $site_name; // My Site 출력

차이점 요약

문법

실패 시

중복 포함 방지

include

경고 (스크립트 계속 진행)

X

require

치명적 에러 (스크립트 종료)

X

include_once

경고

O

require_once

치명적 에러

O


2. namespace — 네임스페이스

PHP의 namespace는 클래스, 함수, 상수의 이름 충돌을 방지하기 위한 기능입니다. 특히 다른 라이브러리나 패키지와 함께 사용할 때 유용합니다.

기본 문법

<?php
namespace MyApp;

class User {
    public function greet() {
        echo "Hello from MyApp\\User";
    }
}

클래스 사용 예 (같은 파일에서)

$user = new \MyApp\User();
$user->greet();

다른 파일로 분리한 경우

파일: User.php

<?php
namespace MyApp;

class User {
    public function greet() {
        echo "Hello from MyApp\\User";
    }
}

파일: index.php

<?php
require 'User.php';

$user = new \MyApp\User();
$user->greet();


3. use 문 — 네임스페이스 줄이기

use 문을 사용하면 긴 네임스페이스 이름을 줄여 쓸 수 있습니다.

<?php
require 'User.php';

use MyApp\User;

$user = new User(); // \MyApp\User 생략 가능
$user->greet();

별칭(alias) 지정

use MyApp\User as AppUser;

$user = new AppUser();


4. 글로벌 네임스페이스

  • PHP는 기본적으로 전역(global) 네임스페이스에서 실행됩니다.

  • namespace를 사용하지 않으면 모든 정의는 전역입니다.

  • 네임스페이스 내에서 전역 함수나 클래스를 사용하려면 \를 붙여야 합니다.

namespace MyApp;

echo \strlen("text"); // 전역 함수 strlen 사용


5. 오토로딩 (include + namespace)

대부분의 현대 PHP 애플리케이션은 클래스 오토로딩을 사용합니다. include 대신 Composer의 autoload 기능을 활용하여 네임스페이스에 따라 클래스를 자동 불러옵니다.

composer init
composer dump-autoload

composer.json 예시:

{
  "autoload": {
    "psr-4": {
      "MyApp\\": "src/"
    }
  }
}

PHP에서 자동 로딩:

require 'vendor/autoload.php';

use MyApp\User;

$user = new User();


요약

기능

설명

include

외부 PHP 파일을 현재 스크립트에 포함

require

include와 같지만 실패 시 치명적 에러

include_once

중복 포함 방지

namespace

클래스나 함수 이름 충돌 방지

use

네임스페이스 줄이기 및 별칭 사용 가능


댓글