Asymmetric visibility in php 8.4: smarter access control for modern code
The PHP 8.4 release (November 2024) introduced Asymmetric Property Visibility, a long-awaited feature that gives developers finer control over how class properties are read and written.
What Is Asymmetric Visibility?
Traditionally, PHP treated property visibility uniformly — a property marked as public, protected, or private applied equally to both reading (get) and writing (set).
PHP 8.4 changes this by allowing different visibility levels for reading and writing a property.
Example:
class User {
public string $name { public get; private set; }
public function __construct(string $name) {
$this->name = $name; // private setter accessible here
}
}
Here, $name is publicly readable but privately writable. This separation ensures controlled updates while maintaining easy access for reading — making encapsulation more powerful and flexible.
Why It Matters
- Enhanced Encapsulation – Developers can keep properties publicly visible but prevent direct external mutation.
- Improved Data Integrity – Logical rules for modification can be enforced only through controlled methods.
- Cleaner APIs – Promotes getter/setter simplification without extra boilerplate code.
- Security and Stability – Reduces accidental overwrites of important internal state values.
Practical Example: Safe BankAccount
class BankAccount {
public int $balance { public get; private set; }
public function __construct(int $initial) {
$this->balance = $initial;
}
public function deposit(int $amount): void {
$this->balance += $amount;
}
}
Here, balance is readable by external code but can only be changed internally — safeguarding financial logic.
Caveats and Notes
- Available only from PHP 8.4 onward.
- Asymmetric visibility is not a replacement for readonly properties; it complements them when controlled mutation is necessary.
- Code editors and static analysis tools are still catching up with full syntax support.
Final Thoughts
Asymmetric visibility marks a major leap in PHP’s object-oriented evolution. It bridges the gap between strict encapsulation and practical readability — a feature that makes PHP 8.4 more expressive, secure, and future‑ready for robust enterprise development.