Private & Protected Properties
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 18 of 91.
So far, we've used public properties that can be accessed from anywhere. But sometimes you need to restrict access to protect your data. PHP provides two additional visibility modifiers: private and protected.
A private property can only be accessed from within the class that defines it:
<?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();
Output:
100Trying to access $account->balance directly from outside the class would cause an error. This protects the balance from being changed without going through the deposit method.
A protected property works similarly, but it can also be accessed by child classes that extend the parent:
<?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();
Output:
admin@example.comKey Point: Use private when only the defining class should access the property. Use protected when child classes also need access. Both prevent direct external access, keeping your object's internal state safe.
Challenge
EasyLet's build a secure employee management system that demonstrates how to protect sensitive data using private and protected properties.
You'll create three files that work together to manage employee information with proper access control:
Employee.php— Define anEmployeeclass that serves as a base for all employees. It should have aprotected $nameproperty (so child classes can access it) and aprivate $salaryproperty (only this class should directly modify salaries). The constructor accepts a name and salary, setting both properties. Add a publicgetName()method that returns the name, a publicgetSalary()method that returns the salary, and a publicgiveRaise($amount)method that increases the salary by the given amount.Manager.php— Define aManagerclass that extendsEmployee. Include the Employee file at the top. Add a private$departmentproperty. The constructor should accept name, salary, and department — call the parent constructor for name and salary, then set the department. Create agetDetails()method that returns"[name] manages [department]"by accessing the protected$nameproperty directly. Also add agetDepartment()method that returns the department.main.php— Include both class files. Create aManagerwith name"Sarah", salary75000, and department"Engineering". Print the manager's details usinggetDetails(). Then give the manager a raise of5000and print their new salary usinggetSalary(). Each output should be on its own line.
Notice how the Manager class can access the protected $name property directly, but must use the getSalary() method to access the private salary. This demonstrates the key difference between protected and private visibility — protected allows child class access while private keeps data truly hidden.
Cheat sheet
PHP provides three visibility modifiers for class properties:
public— accessible from anywhereprivate— accessible only within the defining classprotected— accessible within the defining class and child classes
Private properties:
class BankAccount {
private $balance = 0;
public function deposit($amount) {
$this->balance += $amount;
}
public function getBalance() {
return $this->balance;
}
}Private properties cannot be accessed directly from outside the class. Use public methods to interact with them.
Protected properties:
class User {
protected $email;
public function __construct($email) {
$this->email = $email;
}
}
class Admin extends User {
public function showEmail() {
return $this->email; // Child class can access protected property
}
}Protected properties can be accessed by child classes that extend the parent class.
When to use:
- Use
privatewhen only the defining class should access the property - Use
protectedwhen child classes also need access - Both prevent direct external access, protecting the object's internal state
Try it yourself
<?php
require_once 'Employee.php';
require_once 'Manager.php';
// TODO: Create a Manager with name "Sarah", salary 75000, and department "Engineering"
// TODO: Print the manager's details using getDetails()
// TODO: Give the manager a raise of 5000
// TODO: Print the new salary using 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