Magic methods

Magic methods are hooks with reserved names that the engine calls by itself. In PHP they let an object act like a string, like a function, or like a bag of properties without extra calls in the code that uses it.

__toString

When code tries to use an object as a string, PHP looks for a method named __toString. Without it you get a fatal error, with it you control the output.

The method takes no arguments and must return a string. Keep it short and free of side effects.

<?php class User { public function __construct(private string $name) { } public function __toString(): string { return $this->name; } } $user = new User("Ada"); echo $user, PHP_EOL;

php tostring.php

Ada

Here echo $user calls __toString behind the scenes. String interpolation and concatenation trigger the same method.

__invoke

The __invoke method lets you call an object like a function. It is handy for small service objects, comparators, and middleware handlers.

Define parameters and a return type exactly as you would for a normal method.

<?php class Multiplier { public function __construct(private int $factor) { } public function __invoke(int $value): int { return $value * $this->factor; } } $triple = new Multiplier(3); echo $triple(10), PHP_EOL;

php invoke.php

30

The object keeps the factor and the call passes the value, so the same object can be called many times. A callback that expects a function accepts this object, because PHP calls __invoke when it meets the parentheses.

__get and __set

The methods __get and __set intercept access to inaccessible properties. Frameworks use them for configuration bags and lazy loaded fields.

They run only when normal access fails, so public properties never trigger them.

<?php class Config { private array $data = []; public function __set(string $key, mixed $value): void { $this->data[$key] = $value; } public function __get(string $key): mixed { return $this->data[$key] ?? "none"; } } $config = new Config(); $config->host = "localhost"; echo $config->host, PHP_EOL; echo $config->missing, PHP_EOL;

php getset.php

localhost
none

The write goes into the private array and the read comes back out, although neither line touches the array directly. A key that was never written answers with the fallback of __get instead of a warning.

Add __isset and __unset when you need isset and unset to respect the same storage.

The Stringable interface

Since PHP 8.0 every class with __toString automatically implements the engine interface Stringable. Type hint it when a function needs anything that can convert to text.

It is the clean alternative to accepting only the string type.

<?php class User { public function __construct(private string $name) { } public function __toString(): string { return $this->name; } } function show(Stringable $value): void { echo $value, PHP_EOL; } show(new User("Grace"));

php stringable.php

Grace

The function accepts the object because the class has __toString, and an object without it is refused with a TypeError before the function body runs. Plain strings still fit, because Stringable accepts them too.

Exercises

  1. Give User a __toString that returns the name and the role, and print the object with echo.
  2. Write a Multiplier with a factor of 5 and call it on two values.
  3. Add __isset to Config and check a key that was never written.
  4. Call show() with a plain string. Does it work?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which method does PHP call when an object is used as a string?

    Answer

    __toString

    The engine looks for __toString, and without it the conversion fails with an Error.

  2. What does __invoke make possible?

    Answer

    Calling the object like a function

    The parentheses after the object run __invoke with the arguments of the call.

  3. When does __get run?

    Answer

    When the property is inaccessible or missing

    A public property is read directly, so only a read the class cannot serve reaches __get.

  4. What is Stringable?

    Answer

    An interface that every class with __toString implements

    The engine adds the interface to such a class, so a Stringable type hint accepts the object.

  5. What does this program print? <?php class User { public function __construct(private string $name) { } public function __toString(): string { return $this->name; } } $user = new User("Ada"); echo $user;

    Answer

    Ada

    echo converts the object to a string, and __toString returns the stored name.

  6. What does this program print? <?php class Multiplier { public function __construct(private int $factor) { } public function __invoke(int $value): int { return $value * $this->factor; } } $triple = new Multiplier(3); echo $triple(10);

    Answer

    30

    The call passes 10 to __invoke, which multiplies it by the stored factor of 3.

  7. What does this program print? <?php class Config { private array $data = []; public function __set(string $key, mixed $value): void { $this->data[$key] = $value; } public function __get(string $key): mixed { return $this->data[$key] ?? "none"; } } $config = new Config(); $config->host = "localhost"; echo $config->host, " ", $config->missing;

    Answer

    localhost none

    The written key comes back from the array, and the missing key falls back to the default of __get.

  8. What does this program print? <?php class User { public function __construct(private string $name) { } public function __toString(): string { return $this->name; } } function show(Stringable $value): void { echo $value; } show(new User("Grace"));

    Answer

    Grace

    The class implements Stringable through __toString, and the function echoes the object as a string.

  9. What does this program print? <?php class Plain { } function show(Stringable $value): void { echo $value; } try { show(new Plain()); } catch (TypeError $e) { echo get_class($e); }

    Answer

    TypeError

    An object without __toString is not Stringable, so the argument check throws a TypeError.

  10. What does this program print? <?php class Plain { } $plain = new Plain(); try { echo $plain; } catch (Error $e) { echo get_class($e); }

    Answer

    Error

    PHP cannot convert an object without __toString to a string and throws an Error.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev