SyntaxStudy
Sign Up
PHP Intermediate 9 min read

Magic Methods

Magic methods are special methods with double-underscore prefixes that PHP calls automatically in response to certain actions. They allow you to define custom behaviour for common operations.

  • __toString() — called when an object is cast to string.
  • __get($name) / __set($name, $value) — called for inaccessible property access.
  • __isset($name) / __unset($name) — called by isset() and unset() on inaccessible properties.
  • __invoke() — called when the object is used as a function.
Example
<?php
class MagicBox
{
    private array $data = [];

    // __set: called when assigning to inaccessible property
    public function __set(string $name, mixed $value): void
    {
        echo "__set: $name = " . var_export($value, true) . "
";
        $this->data[$name] = $value;
    }

    // __get: called when reading an inaccessible property
    public function __get(string $name): mixed
    {
        echo "__get: $name
";
        return $this->data[$name] ?? null;
    }

    // __isset: called by isset() / empty() on inaccessible property
    public function __isset(string $name): bool
    {
        return isset($this->data[$name]);
    }

    // __unset: called by unset() on inaccessible property
    public function __unset(string $name): void
    {
        unset($this->data[$name]);
    }

    // __toString: called when object is cast/echoed as string
    public function __toString(): string
    {
        return json_encode($this->data, JSON_PRETTY_PRINT);
    }

    // __invoke: called when object is used as function
    public function __invoke(string $key): mixed
    {
        return $this->data[$key] ?? null;
    }
}

$box = new MagicBox();
$box->name  = 'Alice';   // calls __set
$box->email = 'alice@example.com';

echo $box->name;           // calls __get
echo isset($box->email) ? 'set' : 'not set'; // calls __isset

echo $box;                 // calls __toString
echo $box('name');         // calls __invoke
Pro Tip

Tip: Use magic methods sparingly. __get() and __set() bypass PHP's type system and IDE autocompletion. Prefer explicit typed properties and methods for code that benefits from static analysis.