Hello! Welcome to the next lesson in your journey to PHP mastery.
In our last lesson, we saw how to bring a class blueprint to life by instantiating objects and interacting with their public members using the -> operator. We also had a glimpse of what happens when we try to access a member marked as private—PHP stops us with an error.
Today, we're going to explore that concept in depth. This lesson is all about controlling access to your class's properties and methods using visibility modifiers. By the end of our session, you'll be able to explain and apply public, private, and protected to build more secure, robust, and maintainable object-oriented code. This is a fundamental concept in OOP called encapsulation, and it's a cornerstone of professional development.
1. The Principle of Encapsulation
Encapsulation means bundling the data (properties) and the methods that operate on that data within a single unit (the class), and controlling access to it. Think of it like a car's dashboard. You, the driver, have a public interface: a steering wheel, pedals, and a speedometer. You don't need to—and shouldn't—directly manipulate the engine's fuel injectors or the transmission's gears. Those are private, internal details.
In PHP, we achieve this control with three keywords: public, private, and protected.

Let's get a formal definition for each.
The Oatllo tutorial provides clear, concise definitions of each visibility modifier and explains why they are so important for writing good code. This reading will give you a solid theoretical foundation.
Read the sections 'What are access levels?' and 'Why is it important?'. Focus on the simple one-line definition for each keyword.
Now, let's see these concepts introduced in a video format.
Learn Object Oriented PHP for Beginners | With Examples to Help You Understand! | OOP PHP Tutorial
This clip from Dani Krossing's OOP tutorial introduces visibility modifiers and the core idea of encapsulation.
Watch from 07:43 to 08:45. The presenter explains that visibility modifiers are used to control who has access to the information inside a class.
2. The Three Visibility Modifiers in Action
Let's break down each modifier with code examples to see how they behave.
public: Accessible from Anywhere
As the name suggests, a public property or method can be accessed from anywhere:
- From outside the class instance (e.g.,
_index.php_). - From inside the class itself.
- From a class that inherits from this one.
If you don't specify any visibility, PHP defaults to public.
class User
{
public $username; // Public property
public function getUsername() // Public method
{
return $this->username;
}
}
$user = new User();
$user->username = 'Alice'; // OK: Accessing public property from outside
echo $user->getUsername(); // OK: Calling public method from outside
private: Accessible Only Within the Class
A private member can only be accessed from within the class that defined it. This is the highest level of protection. Neither code outside the class nor any child classes can access it directly.
This is perfect for sensitive data like passwords or for internal "helper" methods that shouldn't be called from anywhere else.
Let's see what happens when we try to break this rule.
Learn Object Oriented PHP for Beginners | With Examples to Help You Understand! | OOP PHP Tutorial
This part of the Dani Krossing video demonstrates the effect of the private keyword and the resulting error when you try to access it from outside.
First, watch from 08:45 to 09:36 to see how a property is declared as private. Then, jump to 20:55 and watch until 22:41 to see the practical result: accessing a public property works, but trying to access a private one causes a fatal error.
So how do we work with private data? We create controlled, public "entry points," often called getters and setters.
The Bitfumes channel provides a very clear and concise example of using a public 'getter' method to provide controlled read-access to a private property. This is a fundamental OOP pattern.
Watch from 01:06 to 02:40. Notice how you can't access $user->password directly, but you can get the value by calling the public getPath() method.
protected: Accessible Within the Class and Its Children
The protected modifier is the middle ground. A protected member can be accessed from within the class itself, just like private. However, it can also be accessed by any class that inherits from it (a "child" or "subclass"). It still cannot be accessed from outside the object instance.
We will cover inheritance in detail in a future module, but for now, just understand that protected is for sharing implementation details with trusted child classes.
This clip clearly demonstrates the behavior of protected. An Admin class extends a User class and is able to access the protected email property, which wouldn't be possible if it were private.
Watch from 02:40 to 05:28. Focus on how the Admin class can access $this->email because it extends User and email is protected.
The official PHP manual provides code examples that demonstrate all three access levels for both properties and methods. It's an excellent reference to solidify your understanding.
The PHP Manual is the ultimate source of truth. These examples clearly show which access attempts work and which result in errors for properties and methods.
Review 'Example #1 Property declaration' and 'Example #5 Method Declaration'. Read the code and the comments to see how PHP enforces visibility rules for an object instance ($obj) and an inheriting class (MyClass2).
3. Best Practices: How to Choose?
Now that you know the rules, how do you decide which modifier to use? Here's a simple, professional rule of thumb:
Start by making everything
private. Only make somethingprotectedorpublicif you have a clear and specific reason to do so.
This "default to private" approach maximizes encapsulation and security. You can always make something less restrictive later, but making it more restrictive can break other parts of your application that depend on it.
Let's watch a practical application of these principles in a class designed to handle database connections—a perfect real-world scenario related to your goal of building secure web applications.
Learn Object Oriented PHP for Beginners | With Examples to Help You Understand! | OOP PHP Tutorial
In this segment, Dani Krossing builds a database handler class and makes deliberate choices about visibility. This is a fantastic example of applying these concepts to a real problem.
Watch from 38:40 to 42:36. Pay close attention to the reasoning: Why are database credentials private? To prevent any outside code from accessing or modifying them. Why is the connect() method protected? Because it's a sensitive operation that should only be available to the class itself and any child classes that need to perform database queries, not to the public.
To wrap up the theory, let's review a list of best practices and common mistakes.
This final reading from the Oatllo tutorial summarizes the key takeaways and provides a checklist of best practices and common pitfalls.
Read the sections 'Best Practices', 'Common Mistakes', and 'Summary'. This is a great way to reinforce what you've learned and get some professional tips.
Conclusion
Excellent work! You now have a solid grasp of one of the most important principles in Object-Oriented Programming. By correctly applying visibility modifiers, you can create code that is more secure, easier to debug, and much simpler to maintain and extend in the long run.
Key Takeaways:
- Encapsulation is the practice of bundling data and methods together and controlling access to them.
publicmembers are accessible from anywhere. This is your class's external "interface".privatemembers are only accessible from within the class that defines them. Use this for sensitive data and internal helper functions.protectedmembers are accessible within the defining class and any child classes that inherit from it.- Best Practice: Default to
privateand only increase visibility (protectedorpublic) when necessary.
Preview of the Next Lesson:
Throughout today's examples, you've seen the $this keyword used repeatedly (e.g., $this->username). This special variable is how an object refers to itself from within its own methods. In our next lesson, we will focus entirely on using the $this keyword to understand precisely how an object manipulates its own properties and calls its own methods, regardless of their visibility.