Public, Protected, Private
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 38 of 91.
Welcome to the Encapsulation chapter! Encapsulation is about controlling access to your class's internal data. PHP provides three access modifiers that determine where properties and methods can be accessed from: public, protected, and private.
Here's how each modifier works:
<?php
class BankAccount {
public $accountHolder; // Accessible from anywhere
protected $accountNumber; // Accessible in this class and child classes
private $balance; // Accessible only in this class
public function __construct($holder, $number, $balance) {
$this->accountHolder = $holder;
$this->accountNumber = $number;
$this->balance = $balance;
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount("John", "12345", 1000);
echo $account->accountHolder . "\n"; // Works - public
echo $account->getBalance(); // Works - public method
Output:
John
1000Trying to access $account->balance directly would cause an error because it's private. The same applies to $account->accountNumber from outside the class hierarchy. This protection ensures that sensitive data can only be modified through controlled methods.
| Modifier | Same Class | Child Class | Outside |
|---|---|---|---|
public | Yes | Yes | Yes |
protected | Yes | Yes | No |
private | Yes | No | No |
Key Point: Use private for internal data that shouldn't be accessed directly, protected for data that child classes need, and public only for safe external access.
Challenge
EasyLet's build a secure employee management system that demonstrates how access modifiers protect sensitive data. You'll create a class hierarchy where different levels of information are accessible depending on where the code is running — inside the class, in a child class, or from outside.
You'll organize your code across three files:
Employee.php— Create anEmployeeclass that manages employee data with appropriate visibility levels. The class should have:- A
publicproperty$namefor the employee's name (safe for anyone to see) - A
protectedproperty$employeeIdfor the internal ID (needed by child classes) - A
privateproperty$salaryfor sensitive pay information (only this class should access it directly)
getSalary()that returns the private salary — this is the controlled way to access protected data. Also add a public methodgetPublicInfo()that returns"[name] works here".- A
Manager.php— Create aManagerclass that extendsEmployee. Include the Employee file. The constructor should accept name, employeeId, salary, and a department name. Call the parent constructor with the first three values, then store the department in a private property. Add a public methodgetTeamInfo()that returns"Manager [name] (ID: [employeeId]) leads [department]". Notice how the child class can access the protected$employeeIdbut would needgetSalary()to access the private salary.main.php— Include the Manager file. You'll receive four inputs: a name, an employee ID, a salary (as a string you'll convert to an integer), and a department name. Create aManagerinstance with these values. Print three lines:- The manager's name accessed directly (public property)
- The result of calling
getTeamInfo() - The result of calling
getSalary()
This challenge shows encapsulation in action: the name is freely accessible, the employee ID is shared with child classes through protected visibility, and the salary remains locked away in the parent class — accessible only through a controlled public method.
Cheat sheet
PHP provides three access modifiers to control where properties and methods can be accessed:
| Modifier | Same Class | Child Class | Outside |
|---|---|---|---|
public | Yes | Yes | Yes |
protected | Yes | Yes | No |
private | Yes | No | No |
Example:
<?php
class BankAccount {
public $accountHolder; // Accessible from anywhere
protected $accountNumber; // Accessible in this class and child classes
private $balance; // Accessible only in this class
public function __construct($holder, $number, $balance) {
$this->accountHolder = $holder;
$this->accountNumber = $number;
$this->balance = $balance;
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount("John", "12345", 1000);
echo $account->accountHolder; // Works - public
echo $account->getBalance(); // Works - public method
Best Practices:
- Use
privatefor internal data that shouldn't be accessed directly - Use
protectedfor data that child classes need - Use
publiconly for safe external access
Try it yourself
<?php
require_once 'Manager.php';
// Read inputs
$name = trim(fgets(STDIN));
$employeeId = trim(fgets(STDIN));
$salary = intval(trim(fgets(STDIN)));
$department = trim(fgets(STDIN));
// TODO: Create a Manager instance with the input values
// TODO: Print the manager's name (accessed directly as public property)
// TODO: Print the result of calling getTeamInfo()
// TODO: Print the result of calling getSalary()
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern