Chapter 12 Β· Going Deeper
Magic Methods
You've already met one method that PHP calls automatically: __construct.
It has siblings! Methods whose names begin with two underscores are magic methods β
PHP invokes them by itself when certain events happen to an object. Learn the handful that matter.
Magic methods are like automatic doors at a shopping mall. Nobody presses a
button β the door "notices" you approaching and reacts on its own. Similarly, you never call
__toString() yourself; PHP notices you treating an object like text and calls it
for you.
__toString β when an object is treated as text
Try to echo an object and PHP normally crashes ("Object could not be converted to
string"). Give the class a __toString() method, and instead PHP politely asks the
object: "how would you like to appear as text?"
<?php
class Money {
public function __construct(private float $amount) {}
public function __toString(): string {
return "K" . number_format($this->amount, 2);
}
}
$fee = new Money(4500.5);
echo "Your balance is $fee"; // PHP silently calls $fee->__toString()
This is the most useful magic method after the constructor β perfect for invoices, dates, names, and anything that has one obvious text form.
__get and __set β the receptionists for unknown properties
These run when code touches a property that doesn't exist (or is invisible from outside).
Frameworks like Laravel use them heavily β it's how $user->name can secretly fetch
data from a database row:
class Settings {
private array $data = [];
public function __set(string $name, $value): void {
echo "(saving '$name')<br>";
$this->data[$name] = $value;
}
public function __get(string $name) {
return $this->data[$name] ?? "not set";
}
}
$config = new Settings();
$config->theme = "dark"; // no $theme property exists β __set runs
echo $config->theme; // __get runs
echo "<br>" . $config->language;
(The ?? is the "null coalescing" operator: "use the left side, but if it doesn't
exist or is null, use the right side instead". You will use it constantly with form data later.)
Magic getters/setters make code harder to follow β your editor can't autocomplete properties
that don't really exist. Prefer real properties and normal getters/setters for your own classes;
understand __get/__set mainly so framework behaviour doesn't mystify you.
__call β catching calls to missing methods
class Api {
public function __call(string $method, array $args) {
return "You tried to call '$method' with " . count($args) . " argument(s).";
}
}
$api = new Api();
echo $api->fetchStudents("2026", "active"); // no such method β __call catches it
The quick reference table
| Magic method | PHP calls it when⦠| How often you'll use it |
|---|---|---|
__construct() | An object is created with new | Constantly βββ |
__toString() | An object is echoed / used as a string | Often ββ |
__get($name) | Reading an inaccessible/missing property | Reading frameworks β |
__set($name, $value) | Writing an inaccessible/missing property | Reading frameworks β |
__call($name, $args) | Calling a missing method on an object | Reading frameworks β |
__isset() / __unset() | isset() / unset() on missing properties | Rare |
__destruct() | The object is destroyed | Rare |
Create a class Student with promoted properties $name and
$program, plus a __toString() that returns
"Chanda (BSc Computing)" style text. Put three students in an array and echo each
one directly in a foreach.
Show solution
<?php
class Student {
public function __construct(
public string $name,
public string $program
) {}
public function __toString(): string {
return "$this->name ($this->program)";
}
}
$students = [
new Student("Chanda", "BSc Computing"),
new Student("Mutinta", "LLB"),
new Student("Bwalya", "BBA"),
];
foreach ($students as $s) {
echo $s . "<br>"; // __toString does the work
}
Which magic method runs when you echo an object?
What makes a method "magic" in PHP?
- Magic methods start with
__and are called automatically by PHP. __toString()defines how an object appears when treated as text β very useful.__get/__set/__callintercept access to missing properties/methods β the engine behind framework "magic".- Prefer real properties and explicit methods in your own code; know the magic mainly to read frameworks.
??(null coalescing) provides a fallback value β remember it for forms later.