0
0
PHPprogramming~15 mins

Properties and visibility in PHP - Deep Dive

Choose your learning style9 modes available
Overview - Properties and visibility
What is it?
Properties in PHP are variables that belong to a class and hold data about an object. Visibility controls who can access these properties: public means anyone can access, protected means only the class and its children can access, and private means only the class itself can access. These rules help organize and protect data inside objects. They make sure that parts of your program only use data the way you want.
Why it matters
Without properties and visibility, all data in an object would be open to everyone, which can cause bugs and security problems. Imagine leaving your diary open for anyone to read or change. Visibility helps keep data safe and organized, so your program behaves correctly and is easier to fix or improve. It also helps teams work together by clearly showing which parts of an object are meant to be used outside and which are internal details.
Where it fits
Before learning properties and visibility, you should understand basic PHP syntax and how classes and objects work. After this, you can learn about methods, inheritance, and design patterns that use visibility to build complex, safe programs.
Mental Model
Core Idea
Properties are like labeled boxes inside an object, and visibility is the lock on each box deciding who can open it.
Think of it like...
Think of a house with rooms (properties). Public rooms are like the living room anyone can enter, protected rooms are like bedrooms only family members can enter, and private rooms are like a personal safe only the owner can open.
Object
├─ Public Property (open door)
├─ Protected Property (family-only door)
└─ Private Property (locked safe)
Build-Up - 7 Steps
1
FoundationWhat are properties in PHP classes
🤔
Concept: Properties store data inside objects created from classes.
color = 'red'; echo $myCar->color; // Outputs 'red' ?>
Result
red
Understanding that properties hold data inside objects is the first step to organizing information in your programs.
2
FoundationIntroduction to visibility keywords
🤔
Concept: Visibility keywords control who can access properties: public, protected, private.
Result
Defines three properties with different access levels.
Knowing visibility keywords helps you protect data and control how your program parts interact.
3
IntermediateAccessing public properties from outside
🤔Before reading on: do you think public properties can be changed from outside the class? Commit to your answer.
Concept: Public properties can be accessed and changed from anywhere in the program.
title = 'PHP Basics'; echo $book->title; // Outputs 'PHP Basics' ?>
Result
PHP Basics
Understanding public properties lets you freely share and modify data, but it also means less control over changes.
4
IntermediateProtected properties and inheritance
🤔Before reading on: can a child class access protected properties of its parent? Commit to yes or no.
Concept: Protected properties are accessible inside the class and any class that extends it, but not outside.
type; // Accessing protected property } } $dog = new Dog(); echo $dog->getType(); // Outputs 'Mammal' ?>
Result
Mammal
Knowing protected visibility helps you share data safely within related classes without exposing it everywhere.
5
IntermediatePrivate properties restrict access strictly
🤔Before reading on: can child classes access private properties of their parent? Commit to yes or no.
Concept: Private properties can only be accessed inside the class where they are declared, not even by child classes.
balance; } } class SavingsAccount extends BankAccount { public function tryAccess() { // return $this->balance; // This would cause an error return 'Access denied'; } } $account = new SavingsAccount(); echo $account->getBalance(); // Outputs 1000 echo $account->tryAccess(); // Outputs 'Access denied' ?>
Result
1000Access denied
Understanding private properties enforces strict data hiding, which is crucial for protecting sensitive information.
6
AdvancedUsing getters and setters for control
🤔Before reading on: do you think direct public property access is always safe? Commit to yes or no.
Concept: Getters and setters are methods that control how properties are read or changed, adding validation or logic.
email = $email; } else { echo 'Invalid email'; } } public function getEmail() { return $this->email; } } $user = new User(); $user->setEmail('test@example.com'); echo $user->getEmail(); // Outputs 'test@example.com' $user->setEmail('bad-email'); // Outputs 'Invalid email' ?>
Result
test@example.comInvalid email
Knowing how to use getters and setters helps you protect data integrity while still allowing controlled access.
7
ExpertVisibility and serialization surprises
🤔Before reading on: do private properties get included when an object is converted to JSON? Commit to yes or no.
Concept: Private and protected properties behave differently during serialization and reflection, which can cause unexpected results.
Result
{"price":99.99}
Understanding how visibility affects serialization prevents bugs when saving or sending objects, especially in APIs.
Under the Hood
PHP stores properties inside objects with metadata about their visibility. Public properties are stored plainly and accessible anywhere. Protected and private properties are stored with special internal keys that include the class name to restrict access. When code tries to access a property, PHP checks the current scope and compares it to the property's visibility rules before allowing or denying access. This check happens at runtime, ensuring encapsulation.
Why designed this way?
Visibility was designed to enforce encapsulation, a core principle of object-oriented programming, to protect data and reduce bugs. Early PHP versions had only public properties, which led to fragile code. Adding protected and private allowed developers to hide implementation details and expose only safe interfaces. The design balances flexibility with safety, using runtime checks to keep PHP dynamic and easy to use.
Object Memory
┌─────────────────────────────┐
│ Object Instance             │
│ ┌─────────────┐             │
│ │ Public      │ <─ accessible anywhere
│ ├─────────────┤             │
│ │ Protected   │ <─ accessible in class and subclasses
│ ├─────────────┤             │
│ │ Private     │ <─ accessible only in declaring class
│ └─────────────┘             │
└─────────────────────────────┘

Access Check Flow
Caller Scope ──▶ Visibility Rule ──▶ Allow or Deny Access
Myth Busters - 4 Common Misconceptions
Quick: Can a child class access its parent's private properties directly? Commit to yes or no.
Common Belief:Child classes can access all properties of their parent classes, including private ones.
Tap to reveal reality
Reality:Private properties are only accessible within the class that declares them, not even by child classes.
Why it matters:Assuming child classes can access private properties leads to errors and broken inheritance logic.
Quick: Do public properties guarantee safe data usage without extra checks? Commit to yes or no.
Common Belief:Public properties are safe to use directly without validation because they are open to everyone.
Tap to reveal reality
Reality:Public properties can be changed from anywhere, which can cause invalid or harmful data if not controlled.
Why it matters:Ignoring validation on public properties can cause bugs, security holes, and unpredictable program behavior.
Quick: When serializing an object, do all properties get included in the output? Commit to yes or no.
Common Belief:All properties, regardless of visibility, are included when an object is serialized or converted to JSON.
Tap to reveal reality
Reality:Only public properties are included by default; private and protected properties are excluded unless special methods are used.
Why it matters:Misunderstanding serialization can cause missing data in APIs or saved files, leading to hard-to-find bugs.
Quick: Does changing a protected property from outside the class cause an error? Commit to yes or no.
Common Belief:Protected properties can be accessed and changed from outside the class like public properties.
Tap to reveal reality
Reality:Protected properties cannot be accessed or changed from outside the class or its subclasses; doing so causes errors.
Why it matters:Trying to access protected properties externally breaks encapsulation and causes runtime errors.
Expert Zone
1
Private properties are stored internally with the declaring class name, so two classes can have private properties with the same name without conflict.
2
Using magic methods like __get and __set can override visibility rules, but this can lead to confusing code if not carefully managed.
3
Reflection in PHP can access private and protected properties, which is powerful for debugging or testing but breaks encapsulation if misused.
When NOT to use
Avoid using public properties for sensitive or critical data that requires validation or controlled access; instead, use private properties with getters and setters. Also, do not rely on visibility for security in web applications; use proper authentication and authorization. For data transfer objects, consider using public properties for simplicity but be aware of the risks.
Production Patterns
In real-world PHP applications, private properties combined with getters and setters are common to enforce data integrity. Protected properties are often used in base classes to share data with subclasses. Public properties are usually reserved for simple data containers or value objects. Serialization methods like JsonSerializable interface are implemented to control which properties are exposed in APIs.
Connections
Encapsulation in Object-Oriented Programming
Properties and visibility are the practical tools to implement encapsulation.
Understanding visibility in PHP deepens your grasp of encapsulation, which is key to building maintainable and secure software.
Access Control in Operating Systems
Both use rules to restrict who can access resources, whether data in objects or files in a system.
Seeing visibility like OS permissions helps appreciate why controlling access prevents errors and security issues.
Privacy in Social Interactions
Visibility in code is like personal boundaries in relationships, deciding what information is shared or kept private.
Recognizing this connection helps understand why hiding details inside objects makes programs more trustworthy and easier to work with.
Common Pitfalls
#1Trying to access a private property from outside its class causes an error.
Wrong approach:password; // Error: Cannot access private property ?>
Correct approach:password; } } $user = new User(); echo $user->getPassword(); // Outputs 'secret' ?>
Root cause:Misunderstanding that private properties cannot be accessed directly outside their class.
#2Assuming public properties are always safe to modify directly without checks.
Wrong approach:price = -10; // No validation, invalid price ?>
Correct approach:= 0) { $this->price = $price; } } public function getPrice() { return $this->price; } } $product = new Product(); $product->setPrice(10); // Valid price ?>
Root cause:Not using encapsulation to protect data integrity.
#3Expecting private and protected properties to be included in JSON serialization by default.
Wrong approach:
Correct approach: $this->id, 'name' => $this->name, 'price' => $this->price ]; } } $item = new Item(); echo json_encode($item); // Outputs {"id":1,"name":"Item","price":100} ?>
Root cause:Not understanding how PHP handles visibility during serialization.
Key Takeaways
Properties hold data inside objects, and visibility controls who can access or change that data.
Public properties are open to all, protected properties are limited to the class and its children, and private properties are strictly internal to the class.
Using visibility properly protects data integrity, reduces bugs, and helps organize code clearly.
Getters and setters provide controlled access to private properties, allowing validation and logic.
Understanding how visibility affects serialization and inheritance prevents common errors in real applications.