PHP Magic Methods

PHP Magic Methods

Magic methods are special double-underscore methods that PHP calls automatically in specific situations.

1 - __toString()

class Money {
    public function __construct(
        private float $amount,
        private string $currency = "USD"
    ) {}

    public function __toString(): string {
        return number_format($this->amount, 2) . " " . $this->currency;
    }
}

$price = new Money(9.99);
echo $price;           // 9.99 USD
echo "Total: $price";  // Total: 9.99 USD

2 - __get() / __set() / __isset() / __unset()

class DynamicRecord {
    private array $attributes = [];

    public function __get(string $key): mixed {
        return $this->attributes[$key] ?? null;
    }

    public function __set(string $key, mixed $value): void {
        $this->attributes[$key] = $value;
    }

    public function __isset(string $key): bool {
        return isset($this->attributes[$key]);
    }
}

$rec = new DynamicRecord();
$rec->name = "Alice";
echo $rec->name;          // Alice
echo isset($rec->name) ? "set" : "not set"; // set

3 - __invoke()

class TaxCalculator {
    public function __construct(private float $rate) {}

    public function __invoke(float $price): float {
        return $price * (1 + $this->rate);
    }
}

$calc = new TaxCalculator(0.2); // 20% tax
echo $calc(100); // 120

4 - __call() and __callStatic()

class QueryBuilder {
    public function __call(string $method, array $args): static {
        echo "Calling $method(" . implode(", ", $args) . ")\n";
        return $this;
    }
}

$q = new QueryBuilder();
$q->where("id", 1)->orderBy("name"); // fluent interface

Note: Magic methods are powerful but add indirection. Use them sparingly and document them well. __get()/__set() in particular can make code hard to debug because IDEs cannot resolve the properties.

-Tip-