Magic methods 是特殊的 methods(前缀为 __),PHP 在对对象执行某些操作时会自动调用它们——例如访问未定义的属性、调用未定义的方法或将对象转换为字符串。它们让你可以 hook 到对象行为中并自定义它。
构造函数和常见的生命周期方法
php
{
{ }
{ }
}
class Container {
private array $data = [];
public function __get($name) { // called on reading an INACCESSIBLE/undefined property
return $this->data[$name] ?? null;
}
public function __set($name, $value) { // called on writing one
$this->data[$name] = $value;
}
public function __isset($name): bool { return isset($this->data[$name]); }
}
$c = new Container();
$c->foo = "bar"; // triggers __set('foo', 'bar')
echo $c->foo; // triggers __get('foo') → "bar"
__get/__set 拦截对不存在或不可访问的属性的访问——启用动态属性(由 ORMs、配置对象使用)。
class Api {
public function __call($method, $args) { // called for UNDEFINED method calls
return $this->request($method, $args); // e.g. dynamic API methods
}
public static function __callStatic($method, $args) { /* static version */ }
}
$api->getUsers(); // no getUsers() method → __call('getUsers', [])
__call/__callStatic 拦截对未定义方法的调用——用于流式/动态 API(例如 Laravel 的 query builder、facades)。
class Money {
public function __construct(private float $amount) {}
public function __toString(): string { // when the object is used as a string
return '$' . number_format($this->amount, 2);
}
}
echo new Money(9.5); // "$9.50" — __toString called automatically
class Multiplier {
public function __invoke($x) { return $x * 2; } // makes the object CALLABLE
}
$double = new Multiplier();
$double(5); // 10 — __invoke called
Magic methods 是 PHP 自定义对象行为的重要特性,理解它们在两方面都很有价值:适当地使用它们——以及特别是——理解 PHP 框架如何实现其