PHP 8.4 Release: Property Hooks, Asymmetric Visibility, and Readonly Improvements
PHP 8.4 introduces property hooks for computed properties, asymmetric visibility controls, and enhanced readonly support. Learn how to modernize your codebase with practical examples.
PHP 8.4: A Major Step Forward in Language Ergonomics
PHP 8.4, released in November 2024, represents one of the most significant updates to the language in recent years. While previous versions (8.0, 8.1, 8.2, 8.3) focused heavily on type system maturity and performance, PHP 8.4 shifts attention to developer experience and code elegance. The three headline features—property hooks, asymmetric visibility, and readonly property improvements—collectively make object-oriented PHP substantially more expressive and maintainable.
If you’re managing backend infrastructure, APIs, or full-stack applications in PHP, understanding these features is essential for writing cleaner, more secure code. This guide walks you through each feature with real-world examples and shows how to integrate them into your existing projects.
Why This Release Matters
PHP powers over 76% of all websites with a known server-side language. That scale means language improvements ripple across the ecosystem quickly. PHP 8.4 addresses three pain points that have frustrated developers for years:
-
Computed properties: Previously required verbose getter/setter methods or magic
__get/__setmethods, which were error-prone and hard to refactor. - Visibility control: Properties were either fully public or fully private—there was no clean way to allow reading but restrict writing (or vice versa).
-
Readonly semantics: PHP 8.1 introduced
readonlyproperties, but they had limitations that PHP 8.4 now resolves.
These features align PHP with patterns already common in languages like TypeScript, Python, and Kotlin, making it easier for teams using multiple languages to maintain consistent design principles.
Understanding Property Hooks
What Are Property Hooks?
Property hooks allow you to attach custom get and set logic to class properties without explicitly creating separate methods. They enable computed properties—values that are calculated on-the-fly or validated before assignment—while maintaining the simplicity of property access syntax.
A Real-World Example
Consider a User class with an email address. You want to ensure emails are always stored in lowercase and are validated before assignment:
class User
{
private string $email = '';
public function getEmail(): string
{
return $this->email;
}
public function setEmail(string $value): void
{
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Invalid email');
}
$this->email = strtolower($value);
}
}
$user = new User();
$user->setEmail('[email protected]'); // Verbose, requires dedicated methods
With PHP 8.4 property hooks, the same logic is cleaner and more intuitive:
class User
{
public string $email {
get => $this->email;
set => (
!filter_var($value, FILTER_VALIDATE_EMAIL)
? throw new InvalidArgumentException('Invalid email')
: $this->email = strtolower($value)
);
}
}
$user = new User();
$user->email = '[email protected]'; // Simple, declarative syntax
echo $user->email; // "[email protected]"
Computed Properties
Property hooks truly shine when calculating values dynamically. Imagine a Rectangle class:
class Rectangle
{
public function __construct(
public float $width,
public float $height,
) {}
// Computed property: area is calculated, not stored
public float $area {
get => $this->width * $this->height;
}
}
$rect = new Rectangle(5, 10);
echo $rect->area; // 50 (calculated on access)
Notice there’s no setter for $area—it’s read-only by default. The property is computed from other state, not stored separately.
Advanced: Conditional Logic and Defaults
You can implement sophisticated validation and transformation logic within hooks:
class Product
{
private string $sku = '';
private float $basePrice = 0.0;
private float $discount = 0.0;
public string $sku {
get => strtoupper($this->sku);
set => $this->sku = trim($value) ?: throw new InvalidArgumentException('SKU cannot be empty');
}
public float $discount {
get => $this->discount;
set => (
$value < 0 || $value > 1
? throw new RangeException('Discount must be between 0 and 1')
: $this->discount = $value
);
}
// Computed final price with discount
public float $finalPrice {
get => $this->basePrice * (1 - $this->discount);
}
}
$product = new Product();
$product->sku = ' abc123 ';
$product->discount = 0.2; // 20% discount
echo $product->finalPrice; // Automatically computed
Asymmetric Visibility: Fine-Grained Access Control
The Problem It Solves
In classical OOP, properties have symmetric visibility: if a property is public, both reading and writing are public. PHP 8.4 introduces asymmetric visibility, allowing different access levels for getters and setters on the same property.
Syntax and Use Cases
The syntax extends property declarations:
class BankAccount
{
// Public readable, private writable
public private(set) float $balance = 0.0;
public function deposit(float $amount): void
{
if ($amount <= 0) {
throw new InvalidArgumentException('Deposit must be positive');
}
$this->balance += $amount;
}
public function withdraw(float $amount): void
{
if ($amount > $this->balance) {
throw new RuntimeException('Insufficient funds');
}
$this->balance -= $amount;
}
}
$account = new BankAccount();
$account->deposit(1000);
echo $account->balance; // 1000 (can read)
// $account->balance = 500; // Error! Cannot write
This pattern is invaluable when you need to expose state for inspection while preventing external modification. The class controls all mutations through its interface.
Combining with Property Hooks
Asymmetric visibility pairs powerfully with property hooks:
class User
{
// Public readable, private writable, with validation
public string $email {
get => $this->email;
private(set);
}
public function setEmail(string $value): void
{
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Invalid email format');
}
$this->email = $value;
}
}
$user = new User();
$user->setEmail('[email protected]');
echo $user->email; // OK
// $user->email = 'bad@'; // Error! Setter is private
Enhanced Readonly Properties
What Changed?
PHP 8.1 introduced readonly properties, which can only be assigned once (typically in the constructor). PHP 8.4 improves this by allowing readonly properties to be re-initialized within a class’s initialization method:
// PHP 8.1: Limited re-initialization
class Document
{
public readonly string $id;
public function __construct(string $id)
{
$this->id = $id; // Only assignment allowed
}
// Cannot easily reset the ID, even from within the class
}
PHP 8.4 allows more flexibility while maintaining immutability guarantees for external code.
Getting Started: Migration Path
Step 1: Check Your PHP Version
php -v
# PHP 8.4.0 (cli) or later
If you’re on PHP 8.3 or earlier, upgrade via your package manager or hosting provider.
Step 2: Update Your Codebase Incrementally
You don’t need to refactor everything at once. Property hooks are opt-in. Start with new code or heavily-used classes:
// Before (8.3 and earlier)
class Config
{
private array $data = [];
public function get(string $key, mixed $default = null): mixed
{
return $this->data[$key] ?? $default;
}
public function set(string $key, mixed $value): void
{
$this->data[$key] = $value;
}
}
// After (8.4+)
class Config
{
public function __construct(
private array $data = [],
) {}
public function get(string $key, mixed $default = null): mixed
{
return $this->data[$key] ?? $default;
}
public function set(string $key, mixed $value): void
{
$this->data[$key] = $value;
}
// Property hooks not needed here—only add them where they reduce complexity
}
Step 3: Identify Validation Opportunities
Look for setters that perform validation or transformation:
// Good candidate for property hooks
class Employee
{
private string $title;
public function setTitle(string $title): void
{
if (empty(trim($title))) {
throw new InvalidArgumentException('Title cannot be empty');
}
$this->title = trim($title);
}
public function getTitle(): string
{
return $this->title;
}
}
// Refactored with property hooks
class Employee
{
public string $title {
get => $this->title;
set => empty(trim($value))
? throw new InvalidArgumentException('Title cannot be empty')
: $this->title = trim($value);
}
}
Common Pitfalls and Best Practices
Pitfall 1: Hooks with Expensive Computations
Property hooks execute every time the property is accessed. If your getter performs a database query or API call, you’ll hammer your backend:
// BAD: Queries the database every access
class User
{
public int $postCount {
get => DB::table('posts')->where('user_id', $this->id)->count();
}
}
// BETTER: Cache the value
class User
{
private ?int $cachedPostCount = null;
public int $postCount {
get => $this->cachedPostCount ??= DB::table('posts')
->where('user_id', $this->id)
->count();
}
}
Pitfall 2: Setter Side Effects
Similarly, don’t perform I/O operations in setters without clear documentation:
// RISKY: Property assignment triggers an HTTP request
class User
{
public string $email {
set => (
$this->email = $value,
Http::post('/verify-email', ['email' => $value])
);
}
}
// BETTER: Use explicit methods
class User
{
public string $email;
public function updateAndVerifyEmail(string $email): void
{
$this->email = $email;
Http::post('/verify-email', ['email' => $email]);
}
}
Pitfall 3: Circular Dependencies in Hooks
Be cautious with computed properties that depend on multiple other properties:
// PROBLEMATIC: Can lead to infinite loops
class Point
{
public float $x = 0;
public float $y = 0;
public float $distance {
get => sqrt($this->x ** 2 + $this->y ** 2);
}
}
// OK in this case, but keep it simple
Best Practice: Use Type Hints
Always declare types on properties with hooks:
// GOOD: Clear types enable IDE support and static analysis
class Product
{
public string $name {
get => $this->name;
set => $this->name = trim($value) ?: throw new DomainException('Name required');
}
public float $price {
get => $this->price;
set => $this->price = $value > 0 ? $value : throw new RangeException('Price must be positive');
}
}
Practical Framework Integration
Laravel
If you’re using Laravel, property hooks work seamlessly with Eloquent models:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public string $title {
get => $this->title;
set => $this->title = trim($value) ?: throw new DomainException('Title required');
}
public string $slug {
get => str($this->title)->slug();
set => null; // Computed from title, read-only
}
}
Symfony
In Symfony applications, combine property hooks with Doctrine entity validation:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Entity]
class User
{
#[ORM\Column]
public string $email {
get => strtolower($this->email);
set => $this->email = $value;
}
}
Debugging and Testing Property Hooks
Use the JWT Decoder if you’re validating token claims in a hook, or the JSON Formatter to validate JSON being set on a property:
class APIClient
{
public array $config {
set => (
json_validate($value)
? $this->config = $value
: throw new InvalidArgumentException('Config must be valid JSON')
);
}
}
For validation testing, consider using property hooks with a mock validator:
// Unit test
class UserTest extends TestCase
{
public function testEmailValidation()
{
$user = new User();
$this->expectException(InvalidArgumentException::class);
$user->email = 'invalid-email';
}
public function testEmailNormalization()
{
$user = new User();
$user->email = '[email protected]';
$this->assertEquals('[email protected]', $user->email);
}
}
Performance Implications
Property hooks have minimal runtime overhead in PHP 8.4’s implementation:
- Hook execution: Equivalent to calling a simple method; negligible cost.
- Computed properties: Only computed when accessed (lazy evaluation).
- Memory: No additional memory overhead compared to getter/setter methods.
Benchmarks show that code using property hooks performs similarly to equivalent method-based approaches, with the advantage of cleaner syntax.
Why It Matters for DevOps and Infrastructure Teams
While property hooks are a language feature, they impact deployment and maintenance:
- Code reviews: Cleaner syntax makes property validation logic easier to audit for security issues.
- Type safety: Better static analysis helps catch bugs before production.
- Refactoring confidence: Property hooks can be introduced incrementally without breaking external APIs.
If you’re managing PHP infrastructure, encourage your team to adopt PHP 8.4 and use property hooks to reduce common bugs from missed validation.
Tools to Support Your Migration
When validating user input or transforming data before assignment, use Kloubot’s utilities:
- JSON Formatter: Validate JSON structures before assignment in hooks.
- Regex Tester: Test complex validation patterns before embedding in hooks.
- Base64 Encoder: Encode/decode data transformations in property setters.
- Hash Generator: Generate hashes for computed properties requiring cryptographic operations.
Conclusion
PHP 8.4 brings three powerful features—property hooks, asymmetric visibility, and enhanced readonly properties—that modernize the language and reduce boilerplate code. By adopting these features thoughtfully, you can write more expressive, maintainable, and secure PHP applications.
Start by identifying classes with complex getters and setters, then incrementally refactor them to use property hooks. Test thoroughly, document your reasoning, and you’ll soon wonder how you lived without these features.