use 키워드
Coddy PHP 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 91개 중 11번째.
클래스를 사용할 때마다 전체 namespace 경로를 작성하는 것은 번거로울 수 있습니다. use keyword를 사용하면 파일 상단에서 클래스를 import할 수 있으므로, 짧은 이름으로 이를 참조할 수 있습니다.
\Blog\User를 반복해서 작성하는 대신, 한 번만 import할 수 있습니다:
<?php
use Blog\User;
$user = new User("Alice");
echo $user->name;
같은 이름의 서로 다른 namespace에서 classes가 필요할 때는 as keyword를 사용하여 별칭을 만들 수 있습니다.
<?php
use Blog\User as BlogUser;
use Shop\User as ShopUser;
$blogger = new BlogUser("Alice");
$customer = new ShopUser("alice@example.com");
echo $blogger->name . "\n";
echo $customer->email . "\n";
출력:
Alice
alice@example.com
그룹화된 import를 사용하여 동일한 네임스페이스에서 여러 클래스를 가져올 수도 있습니다:
<?php
use Blog\{User, Post, Comment};
$user = new User("Alice");
$post = new Post("Hello World");
핵심 사항: use 문은 namespace 선언(있는 경우) 뒤에, 다른 코드보다 먼저 나타나야 합니다. 반복되는 namespace 경로를 제거하여 코드를 더 깔끔하고 읽기 쉽게 만듭니다.
챌린지
쉬움use keyword를 사용하여 클래스를 깔끔하게 import하고 곳곳에 전체 namespace 경로를 작성하지 않도록 messaging application을 구성해 보겠습니다.
함께 작동하는 세 개의 files를 만듭니다.
Messaging/Email.php:Messagingnamespace에Emailclass를 Define합니다.public $addressproperty, address를 accepts하고 설정하는 constructor, 그리고"Sending email to [address]"를 returns하는send()method를 가져야 합니다.Messaging/SMS.php:Messagingnamespace에SMSclass를 Define합니다.public $phoneproperty, phone number를 accepts하고 설정하는 constructor, 그리고"Sending SMS to [phone]"를 returns하는send()method를 가져야 합니다.main.php: 두 class files를 Include한 다음,usekeyword를 사용하여 두 classes를 import합니다. address가"alice@example.com"인Emailobject와 phone이"555-1234"인SMSobject를 Create합니다. 각 object에서send()를 calling한 result를 Print합니다(각각 자체 line에 출력).
main.php에서는 new \Messaging\Email(...)을 작성하는 대신, 위쪽에서 use statements로 classes를 import하므로 간단히 new Email(...)과 new SMS(...)를 작성할 수 있습니다.
직접 해보기
<?php
// 클래스 파일들을 포함합니다
require_once 'Messaging/Email.php';
require_once 'Messaging/SMS.php';
// TODO: 'use' 키워드를 사용하여 Messaging 네임스페이스에서 두 클래스를 모두 가져오세요
// 이렇게 하면 'new \Messaging\Email(...)' 대신 'new Email(...)'을 작성할 수 있습니다
// TODO: Create an Email object with address "alice@example.com"
// TODO: 전화번호 "555-1234"로 SMS 객체를 생성하세요
// TODO: 각 객체에서 send()를 호출한 결과를 출력하세요 (각각 별도의 줄에)
?>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러