PHP Magic Methods
In this page:
What are Magic Methods?
Magic methods are special methods PHP calls automatically in response to certain events, always prefixed with a double underscore, like __construct(), __toString(), or __get().
Example: What are Magic Methods?
<?php
class User {
function __construct() {
echo "User created\n";
}
function __toString() {
return "User object";
}
}
$user = new User();
echo $user;
?>
Login to try C/C++/Java/PHP code in the editor
The Constructor and Destructor
__toString() lets an object define what string it should turn into when used in a string context, such as echoing it directly — without it, PHP raises a fatal error trying to convert an object to a string.
Example: The Constructor and Destructor
<?php
class Money {
private $amount;
function __construct($amount) {
$this->amount = $amount;
}
function __toString() {
return "$" . number_format($this->amount, 2);
}
}
echo new Money(19.5);
?>
Login to try C/C++/Java/PHP code in the editor
Property Overloading (__get and __set)
__get() and __set() intercept access to properties that don't exist or aren't accessible normally, letting you implement custom logic (like validation or lazy loading) that runs whenever code reads or writes a virtual property.
Example: Property Overloading (__get and __set)
<?php
class Config {
private $data = [];
function __set($name, $value) {
$this->data[$name] = $value;
}
function __get($name) {
return $this->data[$name] ?? null;
}
}
$config = new Config();
$config->theme = "dark";
echo $config->theme;
?>
Login to try C/C++/Java/PHP code in the editor
Object to String (__toString)
__call() intercepts calls to methods that don't exist on the object, which is how many ORM libraries implement flexible, dynamic-looking method names without literally defining hundreds of real methods.
Example: Object to String (__toString)
<?php
class Model {
function __call($name, $args) {
echo "Called method: $name\n";
}
}
$model = new Model();
$model->getName();
?>
Login to try C/C++/Java/PHP code in the editor
Method Overloading (__call)
Because magic methods run implicitly and aren't visible in a class's normal method list, overusing them can make code harder to trace and debug — they're powerful but best reserved for cases with a genuinely good reason.
Example: Method Overloading (__call)
<?php
class Product {
private $data = [];
function __get($name) {
echo "Reading '$name' via magic method\n";
return $this->data[$name] ?? null;
}
}
$p = new Product();
echo $p->price;
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: