← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Property Hooks (PHP 8.4)

php PHP 8.4+ Advanced

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)));
    }
}

Edited 23 Mar 2026
Views 23
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 2 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 3 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 0 pings F 1 ping S 0 pings S 0 pings M 1 ping T 0 pings W 0 pings T 0 pings F 0 pings S
No pings yet today
No pings yesterday
Amazonbot 7 Perplexity 5 Unknown AI 3 Google 3 ChatGPT 1 Ahrefs 1
crawler 18 crawler_json 1 pre-tracking 1
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

✓ schema.org compliant