Skip to main content

Lesson 5 of 7

Magic Methods - __get, __set, __call & More

Magic methods are special methods PHP calls automatically in certain situations - accessing undefined properties, calling undefined methods, converting to string, cloning, serialising. Used carefully, they enable elegant APIs. Used carelessly, they hide bugs and make code unpredictable.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Essential Magic Methods

Essential Magic Methods
<?php
declare(strict_types=1);

// ── __toString - object to string conversion ──────────────────
class Money {
    public function __construct(
        private readonly int    $amountCents,
        private readonly string $currency = "USD",
    ) {}

    public function __toString(): string {
        return sprintf("%s %.2f", $this->currency, $this->amountCents / 100);
    }

    public function add(Money $other): static {
        if ($this->currency !== $other->currency) {
            throw new InvalidArgumentException("Cannot add different currencies.");
        }
        return new static($this->amountCents + $other->amountCents, $this->currency);
    }
}

$price    = new Money(4999);
echo $price;           // "USD 49.99"
echo "Price: $price";  // "Price: USD 49.99"

// ── __invoke - call object as function ────────────────────────
class PriceFormatter {
    public function __construct(private string $currency = "USD", private int $decimals = 2) {}

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

$format = new PriceFormatter("EUR");
echo $format(49.99);     // "49.99 EUR"
$prices = array_map($format, [9.99, 19.99, 49.99]);

// ── __get and __set - dynamic properties (use sparingly) ──────
class DynamicModel {
    private array $attributes = [];
    private array $dirty      = [];

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

    public function __set(string $name, mixed $value): void {
        if (($this->attributes[$name] ?? null) !== $value) {
            $this->dirty[] = $name;
        }
        $this->attributes[$name] = $value;
    }

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

    public function __unset(string $name): void {
        unset($this->attributes[$name]);
    }

    public function isDirty(): bool { return !empty($this->dirty); }
    public function getDirty(): array { return $this->dirty; }
}

$model = new DynamicModel();
$model->title = "Hello";
$model->author = "Alice";
echo $model->title;         // "Hello"
var_dump(isset($model->author)); // true

// ── __clone - deep clone nested objects ───────────────────────
class PostWithComments {
    public array $comments = [];
    public DateTime $updatedAt;

    public function __clone() {
        // DateTime is an object - clone it too (else both share the same instance)
        $this->updatedAt = clone $this->updatedAt;
        // Arrays of scalars are automatically deep-copied
        // Arrays of objects need explicit cloning:
        $this->comments = array_map(fn($c) => clone $c, $this->comments);
    }
}

Quick Quiz

Tip

Tip

Practice Magic Methods get set call More in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Magic Methods - __get, __set, __call & More

Practice Task

Note

Practice Task - (1) Write a working example of Magic Methods get set call More from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Magic Methods get set call More is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done