PHP Magic Methods
In this page:
class ClassName {
function __construct() { }
function __toString() { return "text"; }
function __get($name) { }
function __set($name, $value) { }
}
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
// Define the class `User`
class User {
// Define the constructor `__construct` with no parameters
function __construct() {
// Print "User created\n" to the output
echo "User created\n";
}
// Define the magic method `__toString` with no parameters
function __toString() {
// Return `"User object"` from this function
return "User object";
}
}
// Create a new `User` instance, stored in `$user`
$user = new User();
// Print `$user` to the output
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
// Define the class `Money`
class Money {
// Declare the private property `$amount`
private $amount;
// Define the constructor `__construct` taking `$amount`
function __construct($amount) {
$this->amount = $amount;
}
// Define the magic method `__toString` with no parameters
function __toString() {
// Return `"$" . number_format($this->amount, 2)` from this function
return "$" . number_format($this->amount, 2);
}
}
// Print `new Money(19.5)` to the output
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
// Define the class `Config`
class Config {
// Declare the private property `$data`, set to `[]`
private $data = [];
// Define the magic method `__set` taking `$name`, `$value`
function __set($name, $value) {
$this->data[$name] = $value;
}
// Define the magic method `__get` taking `$name`
function __get($name) {
// Return `$this->data[$name] ?? null` from this function
return $this->data[$name] ?? null;
}
}
// Create a new `Config` instance, stored in `$config`
$config = new Config();
$config->theme = "dark";
// Print `$config->theme` to the output
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
// Define the class `Model`
class Model {
// Define the magic method `__call` taking `$name`, `$args`
function __call($name, $args) {
// Print "Called method: $name\n" to the output
echo "Called method: $name\n";
}
}
// Create a new `Model` instance, stored in `$model`
$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
// Define the class `Product`
class Product {
// Declare the private property `$data`, set to `[]`
private $data = [];
// Define the magic method `__get` taking `$name`
function __get($name) {
// Print "Reading '$name' via magic method\n" to the output
echo "Reading '$name' via magic method\n";
// Return `$this->data[$name] ?? null` from this function
return $this->data[$name] ?? null;
}
}
// Create a new `Product` instance, stored in `$p`
$p = new Product();
// Print `$p->price` to the output
echo $p->price;
?>
Login to try C/C++/Java/PHP code in the editor
- Forgetting that
__getand__setonly run for inaccessible or missing properties. - Returning something other than a string from
__toString. - Calling a magic method directly instead of relying on PHP to call it.
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: