Magic Methods (__get, __set, __call…)
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]);
}
}
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
15 Mar 2026
Edited
22 Mar 2026
Views
27
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
Amazonbot 6
Perplexity 5
Google 4
SEMrush 4
Unknown AI 2
Ahrefs 2
ChatGPT 2
Majestic 1
Also referenced
How they use it
crawler 22
crawler_json 4
Related categories
⚡
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