0
0
PHPprogramming~15 mins

Access modifiers (public, private, protected) in PHP - Deep Dive

Choose your learning style9 modes available
Overview - Access modifiers (public, private, protected)
What is it?
Access modifiers are keywords in PHP that control how properties and methods of a class can be accessed. They define whether these parts are visible outside the class, only inside the class, or also in classes that inherit from it. The three main modifiers are public, private, and protected, each setting different levels of access.
Why it matters
Without access modifiers, all parts of a class would be open to any code, which can cause bugs and security issues. They help protect data by hiding it and controlling how it is changed or used. This makes programs safer, easier to maintain, and less likely to break when changed.
Where it fits
Before learning access modifiers, you should understand basic PHP classes and objects. After mastering them, you can learn about inheritance, encapsulation, and design patterns that rely on controlling access to class members.
Mental Model
Core Idea
Access modifiers are like gates that decide who can enter and use parts of a class.
Think of it like...
Imagine a house with rooms: public rooms are open to all guests, private rooms are locked and only the owner can enter, and protected rooms can be accessed by the owner and close family members.
Class Access Levels
┌───────────────┐
│   Public      │  <-- Anyone can access
├───────────────┤
│  Protected    │  <-- Class and subclasses only
├───────────────┤
│   Private     │  <-- Class only
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding public access modifier
🤔
Concept: Public members are accessible from anywhere in the program.
color; // Access public property echo $car->drive(); // Call public method ?>
Result
redDriving
Knowing that public members are fully open helps you design parts of a class meant for general use.
2
FoundationUnderstanding private access modifier
🤔
Concept: Private members can only be accessed inside the class itself.
engineNumber; } } $car = new Car(); echo $car->getEngineNumber(); // Works // echo $car->engineNumber; // Error: Cannot access private property // echo $car->startEngine(); // Error: Cannot call private method ?>
Result
12345
Understanding private access protects sensitive data and internal workings from outside interference.
3
IntermediateExploring protected access modifier
🤔
Concept: Protected members are accessible inside the class and by classes that inherit from it.
speed += 10; return $this->speed; } } class Car extends Vehicle { public function speedUp() { return $this->accelerate(); } } $car = new Car(); echo $car->speedUp(); // 10 // echo $car->speed; // Error: Cannot access protected property ?>
Result
10
Protected access allows controlled sharing of data and behavior with child classes while hiding it from the outside world.
4
IntermediateCombining access modifiers in one class
🤔
Concept: A class can have public, private, and protected members together to control access precisely.
balance += $amount; } public function deposit($amount) { if ($amount > 0) { $this->updateBalance($amount); } } public function getBalance() { return $this->balance; } } $account = new BankAccount(); $account->deposit(500); echo $account->getBalance(); // 1500 // echo $account->balance; // Error // echo $account->accountNumber; // Error ?>
Result
1500
Using all three modifiers together helps build safe and clear interfaces for your classes.
5
IntermediateAccess modifiers and inheritance rules
🤔Before reading on: Can a subclass access private members of its parent class directly? Commit to yes or no.
Concept: Private members are not accessible by subclasses, but protected members are.
privateVar; // Error return $this->protectedVar; // Works } } $child = new ChildClass(); echo $child->testAccess(); // protected ?>
Result
protected
Knowing that private members are hidden even from subclasses prevents accidental misuse and bugs.
6
AdvancedUsing access modifiers for encapsulation
🤔Before reading on: Does encapsulation mean hiding all data or controlling access carefully? Commit to your answer.
Concept: Encapsulation uses access modifiers to hide internal details and expose only what is necessary.
Encapsulation means bundling data and methods that operate on that data inside a class, while restricting direct access to some of the object's components. This is done by making properties private or protected and providing public methods to access or modify them safely.
Result
Better control over data integrity and easier maintenance.
Understanding encapsulation helps you design classes that protect their own data and reduce bugs.
7
ExpertReflection and access modifiers in PHP
🤔Before reading on: Can PHP's Reflection API access private and protected members? Commit to yes or no.
Concept: PHP's Reflection API can bypass access modifiers to inspect or modify private and protected members.
getProperty('hidden'); $property->setAccessible(true); // Bypass access echo $property->getValue($secret); // Outputs 'top secret' ?>
Result
top secret
Knowing that access modifiers can be bypassed with Reflection reveals limits of access control and helps in debugging or testing.
Under the Hood
Access modifiers in PHP are enforced by the language engine at runtime. When code tries to access a class member, PHP checks the context: if the access is allowed based on the modifier, it proceeds; otherwise, it throws an error. Private members are stored with metadata that restricts access strictly to the declaring class. Protected members allow access from subclasses by checking inheritance relationships. Public members have no restrictions.
Why designed this way?
PHP adopted access modifiers to support object-oriented principles like encapsulation and inheritance, improving code safety and design clarity. The strict enforcement prevents accidental misuse of internal class details. Alternatives like no access control or only public members were rejected because they lead to fragile and hard-to-maintain code.
Access Check Flow
┌───────────────┐
│ Access Request│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Check Modifier│
├───────────────┤
│ Public?       │─Yes─► Allow Access
│ No            │
│ Private?      │─Yes─► Is Caller Same Class? ──Yes─► Allow
│ No            │
│ Protected?    │─Yes─► Is Caller Class or Subclass? ──Yes─► Allow
│ No            │
└───────────────┘
       │
       ▼
  Deny Access (Error)
Myth Busters - 3 Common Misconceptions
Quick: Does 'private' mean no one outside the class can ever access the member, including subclasses? Commit yes or no.
Common Belief:Private members can be accessed by subclasses because they inherit everything.
Tap to reveal reality
Reality:Private members are only accessible inside the class that declares them, not by subclasses.
Why it matters:Assuming subclasses can access private members leads to errors and broken code when trying to use or override them.
Quick: Is 'protected' the same as 'private' but with a different name? Commit yes or no.
Common Belief:Protected is just a softer form of private, but still mostly hidden.
Tap to reveal reality
Reality:Protected members are accessible by subclasses, making them a key tool for inheritance and extension.
Why it matters:Confusing protected with private causes missed opportunities to design flexible class hierarchies.
Quick: Can access modifiers prevent all ways to access class members in PHP? Commit yes or no.
Common Belief:Access modifiers completely block any external access to private or protected members.
Tap to reveal reality
Reality:PHP's Reflection API can bypass access modifiers, allowing inspection and modification of private and protected members.
Why it matters:Believing access modifiers are absolute security can lead to false confidence and overlooked debugging tools.
Expert Zone
1
Private members are stored per class, so if a subclass declares a private member with the same name, it is a different property, not an override.
2
Using protected members carefully allows subclasses to extend behavior without exposing internals to the outside world.
3
Reflection can be used in testing frameworks to access private members, but relying on it in production code breaks encapsulation.
When NOT to use
Avoid using private members when you expect subclasses to need access; use protected instead. For simple data containers or value objects, public properties may be acceptable. When strict immutability or API stability is required, consider using readonly properties or interfaces instead of relying solely on access modifiers.
Production Patterns
In real-world PHP applications, access modifiers are used to create clear APIs for classes, hiding implementation details. Frameworks often use protected methods to allow extension points. Private members secure sensitive data like passwords or tokens. Reflection is used in testing and serialization libraries to access non-public members safely.
Connections
Encapsulation
Access modifiers are the main tool to implement encapsulation in object-oriented programming.
Understanding access modifiers deepens your grasp of encapsulation, which is about hiding complexity and protecting data.
Inheritance
Protected access modifier directly supports inheritance by allowing subclasses to access certain members.
Knowing how protected works clarifies how inheritance can be safely used to extend classes.
Security Principles
Access modifiers relate to the principle of least privilege in security, limiting access to only what is necessary.
Seeing access modifiers as a security measure helps appreciate their role beyond just code organization.
Common Pitfalls
#1Trying to access a private property from outside the class.
Wrong approach:name; // Error: Cannot access private property ?>
Correct approach:name; } } $user = new User(); echo $user->getName(); // Alice ?>
Root cause:Misunderstanding that private means inaccessible outside the class, requiring public methods to expose data.
#2Assuming protected members are accessible from outside the class hierarchy.
Wrong approach:type; // Error: Cannot access protected property ?>
Correct approach:type; } } $animal = new Animal(); echo $animal->getType(); // mammal ?>
Root cause:Confusing protected with public, forgetting it restricts access to class and subclasses only.
#3Overusing private when subclasses need access, causing code duplication.
Wrong approach:data; } } class ChildClass extends ParentClass { public function showData() { return $this->getData(); // Error } } ?>
Correct approach:data; } } class ChildClass extends ParentClass { public function showData() { return $this->getData(); // Works } } ?>
Root cause:Not understanding the difference between private and protected and their impact on inheritance.
Key Takeaways
Access modifiers control who can see and use parts of a class, protecting data and behavior.
Public members are open to all, private members are hidden inside the class, and protected members are shared with subclasses.
Using access modifiers properly helps build safer, clearer, and more maintainable code.
Misunderstanding access levels leads to common bugs and design problems, especially with inheritance.
Advanced tools like PHP's Reflection can bypass access modifiers, showing their limits and uses in testing.