Magic Methods: Calls, Strings, Invoking and Serialization

6.Magic Methods: Calls, Strings, Invoking and Serialization

M

In this chapter

We'll learn the magic methods for calls and conversions — __call() and __callStatic() for methods that don't exist, __toString() for turning an object into text, __invoke() for objects you can call like functions, __serialize() and __unserialize() for storage, and __debugInfo() for var_dump() — and how they compare with Ruby's method_missing and Python's __str_, `call` and `eq`_, which have no PHP equivalent.

15–17 min

The Problem in Real Life

LegacyNotifier forwards every method call to the SMS client with a magic __call(). A new reminder script calls $notifier->sendSmss($phone, $text). No error, no warning — and no text reaches the customer: __call() caught the misspelled name, found nothing to forward it to, and returned null.

Mia also wants echo $price; to print "£27.50" instead of failing, and a cleaner var_dump() of a Money object. Both need magic methods too — the useful kind.

M

sendSmss doesn't exist. How can calling it not be an error?

Mia

Methods That Exist vs. Methods Caught at Runtime

Catch-all calls

_call() receives every undefined method name — typos included — exactly like _get() for properties.

Objects as text

__toString() lets echo, string interpolation and string functions use an object.

Objects as functions

__invoke() lets an object be called like a function — and passed wherever a callable is expected.

Magic Methods: Calls, Strings, Invoking and Serialization

The rest of the magic methods: this chapter covers the magic methods for calls, conversions, storage and debugging:

  • __call() and __callStatic(): calls to methods that don't exist.
  • __toString(): an object used as a string.
  • __invoke(): an object used as a function.
  • __serialize(), __unserialize() and __debugInfo(): storing and inspecting objects.
  • Other languages: Ruby's method_missing, Python's __str__, __call__ and __eq__.

__call() and __callStatic(): calling a method that doesn't exist (or isn't visible) on an object calls __call($name, $arguments) instead of failing; on a class, statically, it calls __callStatic(). It's how proxies forward calls to another object, and how Laravel's facades turn Cache::get(...) into a call on a real cache object. The trade-off is the same as __get(): every unknown name is accepted, so sendSmss() "works". Keep __call() strict — forward only names you know, throw BadMethodCallException for the rest — and document the methods with @method doc comments so editors and PHPStan can see them. In your own new code, write real methods instead. The diagram below shows the decision PHP makes on every method call.

What PHP does on $obj->method()

$notifier->sendSmss(...)

a method is called

1

Declared and visible here?

yes → run it

2: if not

Does the class have __call()?

yes → __call("sendSmss", [...]) decides

3: if not

Error: Call to undefined method

the script stops

Mia's bug: __call() swallows a typo
<?php
class LegacyNotifier
{
public function __call(string $name, array $arguments): mixed
{
if ($name === "sendSms") {
echo "SMS to {$arguments[0]}\n";
}
return null; // every other name: silently nothing
}
}
$notifier = new LegacyNotifier();
$notifier->sendSms("+447700900456", "Hi"); // SMS to +447700900456
$notifier->sendSmss("+447700900456", "Hi"); // typo: no error, no SMS
echo "script finished\n"; // script finished
Strict __call(), and __callStatic() for a facade
<?php
declare(strict_types=1);
/** @method void sendSms(string $to, string $text) */
final class Notifier
{
public function __call(string $name, array $arguments): mixed
{
return match ($name) {
"sendSms" => "SMS to {$arguments[0]}: {$arguments[1]}",
default => throw new BadMethodCallException("Notifier has no method $name()"),
};
}
public static function __callStatic(string $name, array $arguments): mixed
{
return (new self())->$name(...$arguments); // a tiny "facade"
}
}
echo Notifier::sendSms("+447700900456", "Hi"), "\n"; // SMS to +447700900456: Hi
try {
(new Notifier())->sendSmss("+447700900456", "Hi");
} catch (BadMethodCallException $e) {
echo $e->getMessage(), "\n"; // Notifier has no method sendSmss()
}

__toString(): when an object is used as a string — echo $price, "Total: $price", strlen($price) — PHP calls its __toString() method, which must return a string. Without one, it's an Error: "Object of class Money could not be converted to string". Since PHP 8.0, every class with __toString() automatically implements the Stringable interface, so a parameter typed string|Stringable accepts it. Use it for a value's natural text form ("£27.50"), not for debugging dumps.

__toString() and Stringable
<?php
declare(strict_types=1);
final readonly class Money
{
public function __construct(public int $pence) {}
public function __toString(): string
{
return "£" . number_format($this->pence / 100, 2);
}
}
$price = new Money(2750);
echo $price, "\n"; // £27.50
echo "Total: $price\n"; // Total: £27.50
var_dump($price instanceof Stringable); // bool(true): automatic since PHP 8.0
final class Plain {}
try {
echo new Plain();
} catch (Error $e) {
echo $e->getMessage(), "\n"; // Object of class Plain could not be converted to string
}

__invoke(): a class with __invoke() makes its objects callable: $surcharge(2750) calls $surcharge->__invoke(2750). Such an object can be passed anywhere a callable is expected — array_map($surcharge, $prices), a callable parameter (Act 09) — and unlike a closure, it can have a class name, constructor, properties and other methods. Act 09's price rules can be invokable classes: new HolidaySurcharge(10) is a rule object you can configure, test and type-check.

__invoke(): a price rule you can call
<?php
declare(strict_types=1);
final readonly class HolidaySurcharge
{
public function __construct(private int $percent) {}
public function __invoke(int $pence): int
{
return $pence + intdiv($pence * $this->percent, 100);
}
}
$rule = new HolidaySurcharge(10);
echo $rule(2750), "\n"; // 3025: called like a function
echo implode(" ", array_map($rule, [2500, 1000])), "\n"; // 2750 1100: passed as a callable
var_dump(is_callable($rule)); // bool(true)

__serialize(), __unserialize() and __debugInfo(): serialize() (Act 11) normally stores every property. A class can take control with __serialize(), which returns an array of exactly what should be stored, and __unserialize(array $data), which rebuilds the object from it — for example to leave out a database connection or a cached value. (They replace the older __sleep()/__wakeup() and the Serializable interface.) __debugInfo() returns the array that var_dump() should show, which is useful to hide secrets or show a readable form. Two more you'll meet: __set_state() for var_export(), and __clone() from Act 11.

__serialize(), __unserialize() and __debugInfo()
<?php
declare(strict_types=1);
final class Customer
{
private ?string $cachedGreeting = null;
public function __construct(public string $name, private string $apiToken) {}
public function __serialize(): array
{
return ["name" => $this->name]; // leave the token and cache out
}
public function __unserialize(array $data): void
{
$this->name = $data["name"];
$this->apiToken = ""; // must be set again by the app
}
public function __debugInfo(): array
{
return ["name" => $this->name, "apiToken" => "***"];
}
}
$clare = new Customer("Clare Lefèvre", "secret-123");
echo serialize($clare), "\n";
var_dump($clare);
// O:8:"Customer":1:{s:4:"name";s:14:"Clare Lefèvre";}
// object(Customer)#1 (2) {
// ["name"]=>
// string(14) "Clare Lefèvre"
// ["apiToken"]=>
// string(3) "***"
// }

All of PHP's magic methods: with this chapter you've met every one of them. PHP has exactly 17 magic methods, and no others may start with two underscores. The table below lists all of them in one place, with the moment PHP calls each — a page worth coming back to whenever you see __something in a class.

Table — All 17 magic methods
MethodPHP calls it when…Where in the course
__construct()new creates an objectAct 11
__destruct()the last reference is goneAct 11
__clone()clone has copied an objectAct 11
__get($name)an inaccessible property is readChapter 5
__set($name, $value)an inaccessible property is writtenChapter 5
__isset($name)isset() or empty() on an inaccessible propertyChapter 5
__unset($name)unset() on an inaccessible propertyChapter 5
__call($name, $args)an inaccessible method is calledThis chapter
__callStatic($name, $args)an inaccessible static method is calledThis chapter
__toString()the object is used as a stringThis chapter
__invoke(...)the object is called like a functionThis chapter
__serialize()serialize() stores the objectThis chapter
__unserialize($data)unserialize() rebuilds itThis chapter
__sleep()serialize(), the older way (returns property names)Legacy: use __serialize()
__wakeup()unserialize(), the older wayLegacy: use __unserialize()
__set_state($props)var_export() output is evaluatedThis chapter
__debugInfo()var_dump() shows the objectThis chapter

Other languages: Ruby's method_missing and Python's __getattr__ for methods are the same idea as __call(). Python's __str__ matches __toString() and __call__ matches __invoke(). But Python has more: __eq__, __lt__, __add__ and others let a class decide what ==, < and + mean, and Java has equals() and compareTo() that collections use. PHP doesn't have magic methods for comparison or operators: == on objects always compares properties (Act 11), and + is a TypeError. Write equals() and compareTo() methods yourself, and use usort() with them (Act 08). The table below lists this chapter's methods.

Table — Magic methods for calls and conversions
MethodPHP calls it when…Python / Ruby equivalent
__call($name, $args)An inaccessible method is called on an objectRuby method_missing
__callStatic($name, $args)An inaccessible static method is called—
__toString()The object is used as a stringPython __str__
__invoke(...)The object is called like a functionPython __call__
__serialize() / __unserialize()serialize() / unserialize()Python __getstate__ / __setstate__
__debugInfo()var_dump() shows the objectPython __repr__ (roughly)
(none in PHP)== or < between objectsPython __eq__ / __lt__, Java equals()
(none in PHP)+ between objectsPython __add__, C++ operator+
Python: __eq__ and __lt__ (no PHP equivalent)
# Python — a class decides what == and < mean
class Money:
def __init__(self, pence): self.pence = pence
def __eq__(self, other): return self.pence == other.pence
def __lt__(self, other): return self.pence < other.pence
prices = [Money(2750), Money(1000)]
print(sorted(prices)[0].pence) # 1000 — sorted() uses __lt__
print(Money(2500) == Money(2500)) # True — uses __eq__
# PHP: write equals() and compareTo() methods, and usort($prices, fn($a, $b) => $a->compareTo($b)).

Key Takeaway

__call() and __callStatic() catch calls to missing methods — they power proxies and Laravel facades, but accept typos; keep them strict and document with @method. __toString() makes an object usable as a string (and Stringable); __invoke() makes it callable, so rule objects can be passed as callbacks. __serialize()/__unserialize() control what's stored; __debugInfo() controls var_dump(). Ruby's method_missing and Python's __str_/`call` have PHP equivalents, but PHP has no magic methods for == or operators (Python `eq`/`add`_) — write equals() and plus() methods.

Why This Matters

__call(), __callStatic() and __get() are how much of Laravel works behind the scenes — facades, models, query builders — so recognising them explains a lot of "how does this even work?". Their silent acceptance of typos is also why Laravel ships @method and @property docblocks and IDE helper tools.

__toString() and __invoke() are the everyday, safe magic: value objects that print themselves and rule objects that work as callbacks. And knowing that PHP has no __eq__ or __add__ saves you from looking for them.

LegacyNotifier is gone; the new Notifier throws for unknown methods, and Money prints itself. Back to the first problem of the Act: the log is still full of "Deprecated: Creation of dynamic property Booking::$note". And Mia's Customer class has grown six getters and setters, one of which forgets to trim the phone number. PHP 8.4 has a better way for both. That's the next chapter: dynamic properties, property hooks and asymmetric visibility.