I magic methods permettono di intercettare operazioni sugli oggetti.
__construct e __destruct
class File {
private $handle;
public function __construct($path) {
$this->handle = fopen($path, "r");
}
public function __destruct() {
fclose($this->handle);
}
}__get e __set
class User {
private $data = [];
public function __get($name) {
return $this->data[$name] ?? null;
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
}
$user = new User();
$user->name = "Mario"; // Chiama __set
echo $user->name; // Chiama __get__toString
public function __toString(): string {
return $this->name;
}