OOP — Magic Methods
6 min read
Magic methods start with double underscores like __construct(), __toString(), and __get(). PHP calls them automatically in specific situations. They let you control how objects behave when converted to strings or cloned.
Magic Methods
class MagicBox {
private array $data = [];
// Called when reading inaccessible property
public function __get(string $key): mixed {
return $this->data[$key] ?? null;
}
// Called when writing inaccessible property
public function __set(string $key, mixed $val): void {
$this->data[$key] = $val;
}
// Called with isset() on inaccessible property
public function __isset(string $key): bool {
return isset($this->data[$key]);
}
// Called when object used as string
public function __toString(): string {
return json_encode($this->data);
}
// Called when object used as function
public function __invoke(string $key): mixed {
return $this->data[$key];
}
// Clone
public function __clone(): void {
$this->data = array_map(fn($v) => $v, $this->data);
}
}
$box = new MagicBox();
$box->name = "Alice"; // __set
echo $box->name; // __get → Alice
echo $box; // __toString → {"name":"Alice"}
echo $box("name"); // __invoke → Alice