Private 및 Protected 속성
Coddy PHP 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 91개 중 18번째.
지금까지는 어디에서나 Access할 수 있는 public property를 사용했습니다. 하지만 때로는 데이터를 보호하기 위해 access를 제한해야 합니다. PHP는 두 가지 추가 visibility modifier인 private와 protected를 제공합니다.
private 속성은 해당 속성을 정의한 클래스 내부에서만 액세스할 수 있습니다:
<?php
class BankAccount {
private $balance = 0;
public function deposit($amount) {
$this->balance += $amount;
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount();
$account->deposit(100);
echo $account->getBalance();
출력:
100클래스 외부에서 직접 $account->balance에 Access하려고 하면 오류가 발생합니다. 이렇게 하면 deposit method를 거치지 않고 balance가 변경되는 것을 방지할 수 있습니다.
protected 속성은 비슷하게 작동하지만, 부모 클래스를 확장하는 자식 클래스에서도 액세스할 수 있습니다.
<?php
class User {
protected $email;
public function __construct($email) {
$this->email = $email;
}
}
class Admin extends User {
public function showEmail() {
return $this->email;
}
}
$admin = new Admin("admin@example.com");
echo $admin->showEmail();
출력:
admin@example.com핵심 요점: 속성에 정의한 클래스만 액세스해야 할 때 private를 사용하세요. 자식 클래스도 액세스해야 할 때는 protected를 사용하세요. 둘 다 외부에서 직접 액세스하는 것을 방지하여 객체의 내부 상태를 안전하게 유지합니다.
챌린지
쉬움private 및 protected property를 사용하여 민감한 데이터를 보호하는 방법을 보여 주는 안전한 Employee 관리 시스템을 만들어 보겠습니다.
적절한 access control을 사용하여 Employee 정보를 관리하기 위해 함께 작동하는 세 개의 파일을 만듭니다:
Employee.php: 모든 Employee의 기반 역할을 하는Employeeclass를 Define합니다.protected $nameproperty(따라서 Child class가 access할 수 있음)와private $salaryproperty(이 class만 salary를 directly 수정해야 함)를 가져야 합니다. constructor는 name과 salary를 accepts하여 두 property를 설정합니다. name을 returns하는 publicgetName()method, salary를 returns하는 publicgetSalary()method, 그리고 주어진 amount만큼 salary를 증가시키는 publicgiveRaise($amount)method를 추가합니다.Manager.php:Employee를 extends하는Managerclass를 Define합니다. 파일 상단에 Employee 파일을 Include합니다. private$departmentproperty를 추가합니다. constructor는 name, salary, department를 accepts해야 합니다.parent::__construct($name, $salary)를 사용하여 parent constructor를 call한 다음 department를 설정합니다. protected$nameproperty에 directly access하여"[name] manages [department]"를 returns하는getDetails()method를 Create합니다. 또한 department를 returns하는getDepartment()method를 추가합니다.main.php: 두 class 파일을 모두 Include합니다. name"Sarah", salary75000, department"Engineering"으로Manager를 Create합니다.getDetails()를 사용하여 manager의 details를 Print합니다. 그런 다음 manager에게5000의 raise를 Give하고getSalary()를 사용하여 새로운 salary를 Print합니다. 각 출력은 자체 줄에 표시되어야 합니다.
Manager class가 protected $name property에 directly access할 수 있지만, private salary에 access하려면 getSalary() method를 사용해야 한다는 점에 주목하세요. 이는 protected와 private visibility의 핵심 차이를 보여 줍니다. protected는 Child class access를 허용하는 반면 private는 데이터를 진정으로 숨겨 둡니다.
직접 해보기
<?php
require_once 'Employee.php';
require_once 'Manager.php';
// TODO: 이름이 "Sarah", 급여 75000, 부서 "Engineering"인 Manager를 생성하세요
// TODO: getDetails()를 사용하여 매니저의 상세 정보를 출력하세요
// TODO: 매니저에게 5000의 인상을 주세요
// TODO: getSalary()를 사용하여 새 급여를 출력하세요
?>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러