What Are Magic Methods in PHP?
Magic methods are special methods prefixed with __ (like __construct or __get) that PHP calls automatically in specific circumstances, letting a class custom...
Published November 22, 2026
PHP magic methods are special methods starting with double underscores, like __construct, __get and __toString, that PHP calls automatically on certain events such as creating an object, reading an inaccessible property or converting to a string.
The concept
Common ones: __construct/__destruct (lifecycle), __get/__set (inaccessible properties), __call/__callStatic (undefined methods), __toString (string conversion), __invoke (calling an object as a function).
Laravel relies heavily on them, for example Eloquent models use __get to expose attributes.
Event → method
Practical examples
__get and __set
class Bag {
private array $d = [];
public function __get($k) { return $this->d[$k] ?? null; }
public function __set($k, $v) { $this->d[$k] = $v; }
}
$b = new Bag; $b->color = 'red'; echo $b->color;__toString and __invoke
class Money {
function __construct(private int $c) {}
function __toString(): string { return number_format($this->c / 100, 2); }
function __invoke($x) { return $x + $this->c; }
}__call proxy
public function __call($name, $args) { return $this->inner->$name(...$args); }Common mistakes
- Overusing __get/__set, hiding the real API.
- Forgetting performance cost.
- Not declaring properties, which breaks IDE help.
Key takeaways
- Auto-called hooks.
- Great for proxies and fluent APIs.
- Use sparingly.
FAQ
What is __clone?
Called when an object is cloned.
Are they slow?
A bit slower than normal access; fine in most code.