PHP Magic Methods: __construct, __get, __call, and More

PHP’s “magic methods” — prefixed with double underscores — let objects hook into language-level behavior like construction, property access, and string conversion. Powerful, but easy to overuse into unreadable code.

class Config {
    private array $data = [];

    public function __construct(array $data) {
        $this->data = $data;
    }

    // Called when accessing an undefined property: $config->timeout
    public function __get($name) {
        return $this->data[$name] ?? null;
    }

    // Called when the object is used in a string context
    public function __toString(): string {
        return json_encode($this->data);
    }

    // Called on undefined method calls
    public function __call($name, $args) {
        throw new BadMethodCallException("Method $name does not exist");
    }
}

$config = new Config(['timeout' => 30]);
echo $config->timeout;   // triggers __get
echo $config;             // triggers __toString

Use magic methods sparingly — they make code harder to trace with IDE navigation, since there’s no explicit method definition to jump to. Reserve them for genuinely generic wrapper classes, not everyday business logic.