Property Hooks (PHP 8.4)
TL;DR
PHP 8.4 property hooks attach get/set logic directly to a property declaration — eliminating getter/setter method boilerplate for common validation and transformation patterns.
Explanation
Syntax: public string $name { get { return $this->name; } set(string $value) { $this->name = trim($value); } }. Shorthand set: set => trim($value). Virtual properties (no backing storage): public string $fullName { get => "$this->first $this->last"; }. A property with only get is implicitly read-only from outside. Abstract hooks in abstract classes and interfaces define contracts. Hooks interact with readonly: readonly properties can only have get hooks (PHP 8.4 allows set in clone). Backed vs virtual: backed has storage, virtual derives. Constructor promotion works with hooks.
Common Misconception
✗ Property hooks replace all getters/setters — they're best for simple per-property logic. Complex cross-property logic or side effects still belong in explicit methods.
Why It Matters
Property hooks reduce boilerplate for the most common getter/setter patterns (trim, normalise, format) while keeping complex logic in methods.
Common Mistakes
- Putting complex business logic in hooks — keep hooks simple.
- Using hooks where readonly would suffice.
- Forgetting virtual properties cannot be set directly.
Code Examples
✗ Vulnerable
class User {
private string $_name;
public function getName(): string { return $this->_name; }
public function setName(string $v): void { $this->_name = trim($v); }
}
✓ Fixed
// PHP 8.4:
class User {
public string $name { set => trim($value); }
// Virtual — no backing storage:
public string $initials {
get => implode('', array_map(fn($w) => $w[0], explode(' ', $this->name)));
}
}
Tags
🤝 Adopt this term
£79/year · your link shown here
Edited
23 Mar 2026
Views
23
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 7
Perplexity 5
Unknown AI 3
Google 3
ChatGPT 1
Ahrefs 1
Also referenced
How they use it
crawler 18
crawler_json 1
pre-tracking 1
Related categories
⚡
DEV INTEL
Tools & Severity
🔵 Info
⚙ Fix effort: Medium
⚡ Quick Fix
Replace simple getter/setter pairs with property hooks. Use set => expr shorthand. Keep complex logic in methods.
📦 Applies To
PHP 8.4+
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
get[A-Z][a-z]+\(\).*return|set[A-Z][a-z]+\(
Auto-detectable:
✗ No
phpstan
🤖 AI Agent
Confidence: Low
False Positives: High
✗ Manual fix
Fix: Medium
Context: Class