Magic methods
| __toString | |
| __invoke | |
| __get and __set | |
| The Stringable interface |
__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.
class User { public function __construct(private string $name) {} public function __toString(): string { return $this->name; } } $user = new User("Ada"); echo $user;
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.
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);
__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.
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;
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.
function show(Stringable $value): void { echo $value; } show(new User("Grace"));
Next: Attributes
Article author: Arthur Isaev