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

Magic Methods (__get, __set, __call…)

PHP PHP 5.0+ Intermediate
debt(d5/e5/b5/t7)
d5 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'specialist tool catches it' (d5). The detection_hints list phpstan and psalm — both specialist static analysis tools — as the means to detect __get/__set hiding class properties. A default linter won't catch the misuse; it requires running phpstan or psalm with appropriate strictness levels to surface the opacity introduced by magic methods.

e5 Effort Remediation debt — work required to fix once spotted

Closest to 'touches multiple files / significant refactor in one component' (e5). The quick_fix suggests avoiding __get/__set entirely and replacing them with explicit typed properties. Removing magic methods from a class requires identifying all callers relying on dynamic property access, adding explicit properties, and updating type hints — a non-trivial refactor within or across a component, but not a full architectural rework.

b5 Burden Structural debt — long-term weight of choosing wrong

Closest to 'persistent productivity tax' (b5). Magic methods apply across web, cli, and queue-worker contexts and carry a persistent tax: IDEs lose autocomplete, static analysis tools lose visibility, and every future maintainer must mentally model the hidden dynamic behaviour. It slows many work streams but doesn't necessarily define the entire system's shape.

t7 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'serious trap — contradicts how a similar concept works elsewhere' (t7). The misconception field explicitly captures the trap: developers believe __get/__set provide good flexible property access, but the 'obvious' usage actively harms discoverability, type safety, and tooling. Additionally, __toString() throwing exceptions silently fails in PHP < 8, and __clone() not deep-copying is a well-known gotcha that contradicts expectations from other OO languages. Multiple serious behavioural surprises elevate this above t5.

About DEBT scoring →

Also Known As

PHP magic methods __construct __destruct __get __set __call

TL;DR

Special PHP methods invoked automatically in response to language events — property access, method calls, serialisation, and more.

Explanation

PHP magic methods include __construct/__destruct (lifecycle), __get/__set/__isset/__unset (property overloading), __call/__callStatic (method overloading), __toString (string casting), __invoke (callable objects), __clone (copy construction), and __wakeup/__sleep/__serialize/__unserialize (serialisation). Magic methods can dramatically simplify APIs but also hide bugs, complicate static analysis, and create security risks — __toString XSS, __wakeup object injection. Use them intentionally and document their behaviour clearly.

Common Misconception

Magic methods like __get and __set are a good way to add flexible property access. Overusing magic methods makes classes opaque to static analysis tools, IDEs, and other developers — explicit properties with proper types are preferable except in specific cases like proxies and ORMs.

Why It Matters

PHP magic methods are implicitly called by the runtime for specific operations — misusing them creates hidden behaviour that violates the principle of least astonishment and is hard to debug.

Common Mistakes

  • __get() and __set() that silently create properties instead of throwing on undefined access — masks typos.
  • __toString() that throws an exception — PHP does not allow exceptions from __toString() prior to PHP 8.
  • __clone() not deep-copying nested objects — the cloned object shares references with the original.
  • Heavy logic in __construct() — makes the class hard to instantiate in tests and violates single responsibility.

Code Examples

✗ Vulnerable
// __get silently swallows undefined property access:
class Config {
    public function __get(string $key): mixed {
        return $this->data[$key] ?? null; // Returns null for any typo — no error
    }
}
$config->databse_host; // Typo — silently returns null instead of error
✓ Fixed
class Collection {
    private array $items = [];

    public function __construct(array $items = []) {
        $this->items = $items;
    }

    // Called when accessing inaccessible/undefined property
    public function __get(string $name): mixed {
        return $this->items[$name] ?? null;
    }

    // Called when setting inaccessible/undefined property
    public function __set(string $name, mixed $value): void {
        $this->items[$name] = $value;
    }

    // Called by echo / string cast
    public function __toString(): string {
        return implode(', ', $this->items);
    }

    // Called by var_dump — PHP 8.2+
    public function __debugInfo(): array {
        return ['count' => count($this->items)];
    }

    // Called when object used as function
    public function __invoke(mixed $item): static {
        return new static([...$this->items, $item]);
    }
}

Added 15 Mar 2026
Edited 22 Mar 2026
Views 61
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 1 ping W 1 ping T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 3 pings F 0 pings S 2 pings S 2 pings M 1 ping T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 2 pings M 0 pings T 1 ping W 0 pings T 0 pings F 0 pings S 1 ping S 0 pings M 2 pings T 0 pings W
No pings yet today
PetalBot 2
Amazonbot 7 SEMrush 7 Google 6 Perplexity 5 ChatGPT 5 Scrapy 5 Ahrefs 4 Majestic 2 Unknown AI 2 Claude 2 Bing 2 PetalBot 2 Meta AI 1
crawler 43 crawler_json 7
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Medium
⚡ Quick Fix
Add return types and parameter types to magic methods (__get, __set, __call); avoid __get/__set — they hide properties from static analysis tools
📦 Applies To
PHP 5.0+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
__get or __set overrides that hide class properties from IDE and static analysis
Auto-detectable: ✓ Yes phpstan psalm
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✗ Manual fix Fix: Medium Context: Class Tests: Update


✓ schema.org compliant