Magic Methods Overview
Learn __toString, __get, __set, and other PHP magic methods.
Magic Methods Overview is a free PHP Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Introduction: PHP Magic Methods
Magic methods are special PHP methods with double-underscore prefixes that are automatically triggered by the PHP engine in specific situations. They give you hooks into object behavior.
Core Concepts
PHP Magic Methods key concepts:
__toString()— object to string conversion__get/__set/__isset/__unset— property access intercepts__call/__callStatic— method call intercepts__invoke()— callable object
__toString
Example:
<?php
class Money {
public function __construct(
private float $amount,
private string $currency
) {}
public function __toString(): string {
return number_format($this->amount, 2) . ' ' . $this->currency;
}
}
$price = new Money(9.99, 'USD');
echo $price; // 9.99 USD
echo 'Price: ' . $price; // Price: 9.99 USD__get and __set
Continued:
<?php
class DynamicObject {
private array $data = [];
public function __get(string $name): mixed {
return $this->data[$name] ?? null;
}
public function __set(string $name, mixed $value): void {
$this->data[$name] = $value;
}
}
$obj = new DynamicObject();
$obj->name = 'Alice';
echo $obj->name; // Alice__isset and __unset
Practice:
<?php
class Model {
private array $attributes = [];
public function __set(string $k, mixed $v): void { $this->attributes[$k] = $v; }
public function __get(string $k): mixed { return $this->attributes[$k] ?? null; }
public function __isset(string $k): bool { return isset($this->attributes[$k]); }
public function __unset(string $k): void { unset($this->attributes[$k]); }
}
$m = new Model();
$m->email = 'a@b.com';
var_dump(isset($m->email)); // true
unset($m->email);
var_dump(isset($m->email)); // false__call and __callStatic
Deeper:
<?php
class FluentQuery {
private array $clauses = [];
public function __call(string $name, array $args): static {
$this->clauses[$name] = $args[0] ?? null;
return $this;
}
public function toSql(): string {
return 'SELECT * FROM '
. ($this->clauses['from'] ?? 'unknown');
}
}
echo (new FluentQuery())->from('users')->toSql();
// SELECT * FROM users__invoke
Advanced usage:
<?php
class Multiplier {
public function __construct(private float $factor) {}
public function __invoke(float $value): float {
return $value * $this->factor;
}
}
$double = new Multiplier(2);
echo $double(5); // 10
echo $double(21); // 42
$funcs = [new Multiplier(2), new Multiplier(3)];
foreach ($funcs as $fn) echo $fn(4) . ' '; // 8 12__clone
Real-world pattern:
<?php
class Config {
private array $data = [];
public function set(string $k, mixed $v): self {
$this->data[$k] = $v;
return $this;
}
public function __clone() {
// deep clone nested objects if needed
}
}
$original = (new Config())->set('theme', 'dark');
$copy = clone $original; // triggers __clone__debugInfo
Best practices:
<?php
class ApiClient {
public function __construct(
private string $baseUrl,
private string $apiKey // sensitive!
) {}
public function __debugInfo(): array {
return [
'baseUrl' => $this->baseUrl,
'apiKey' => '***' . substr($this->apiKey, -4), // mask key
];
}
}
var_dump(new ApiClient('https://api.example.com', 'secret123'));
// Shows masked keyPractical Pattern
Putting it all together with a practical pattern for PHP Magic Methods.
Common Pitfalls
Avoid these common mistakes with PHP Magic Methods:
- Use __toString() so objects print meaningfully
- __get/__set enable proxy/decorator patterns
- __invoke makes objects work as callables (useful with array_map)
- __debugInfo prevents sensitive data appearing in var_dump
Quick Check
What magic method makes a PHP object callable like a function?
Recap: PHP Magic Methods
You've covered PHP Magic Methods. Key points to remember:
- Use __toString() so objects print meaningfully
- __get/__set enable proxy/decorator patterns
- __invoke makes objects work as callables (useful with array_map)
- __debugInfo prevents sensitive data appearing in var_dump
Frequently asked questions
Is the “Magic Methods Overview” lesson free?
Yes — the full text of “Magic Methods Overview” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Magic Methods Overview”?
Learn __toString, __get, __set, and other PHP magic methods. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Magic Methods Overview” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.