Kritim Yantra
May 18, 2025
When learning PHP, you may come across special methods that start with double underscores (__
). These are known as magic methods. They’re called “magic” not because they do anything supernatural, but because PHP automatically calls them in certain situations.
Magic methods allow you to customize object behavior, make your code cleaner, and handle special cases like debugging, serialization, method calls, and more.
In this post, you’ll learn:
Magic methods in PHP are predefined methods that start with __
(double underscore). PHP automatically calls these methods when specific operations are performed on an object.
For example:
__toString()
__destruct()
They are defined inside a class and are not called directly. PHP triggers them behind the scenes.
Magic Method | Triggered When... |
---|---|
__construct() |
A new object is created |
__destruct() |
An object is destroyed |
__call() |
Calling inaccessible or undefined method |
__callStatic() |
Calling inaccessible or undefined static method |
__get() |
Reading data from inaccessible or undefined property |
__set() |
Writing data to inaccessible or undefined property |
__isset() |
Using isset() or empty() on inaccessible property |
__unset() |
Using unset() on inaccessible property |
__toString() |
Converting object to a string (e.g., echo $obj ) |
__invoke() |
When object is used as a function |
__clone() |
When object is cloned |
__sleep() |
Before serialization |
__wakeup() |
After unserialization |
__debugInfo() |
When using var_dump() on object |
Let’s dive into each one with examples.
__construct()
and __destruct()
__construct()
: ConstructorThis method is automatically called when a new object is created.
class User {
public function __construct() {
echo "User created!<br>";
}
}
$user = new User(); // Output: User created!
__destruct()
: DestructorThis method is called when the object is destroyed or the script ends.
class User {
public function __destruct() {
echo "User destroyed!<br>";
}
}
$user = new User();
unset($user); // Output: User destroyed!
__get()
and __set()
Used to get or set inaccessible (private/protected) or non-existent properties.
class Product {
private $data = [];
public function __get($name) {
return $this->data[$name] ?? null;
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
}
$p = new Product();
$p->price = 100;
echo $p->price; // Output: 100
__call()
and __callStatic()
These methods handle calls to undefined or inaccessible methods.
__call()
: For object methodsclass Magic {
public function __call($name, $arguments) {
echo "Calling method '$name' with args: " . implode(', ', $arguments) . "<br>";
}
}
$obj = new Magic();
$obj->sayHello('John'); // Output: Calling method 'sayHello' with args: John
__callStatic()
: For static methodsclass Magic {
public static function __callStatic($name, $arguments) {
echo "Calling static method '$name' with args: " . implode(', ', $arguments) . "<br>";
}
}
Magic::sayHi('PHP'); // Output: Calling static method 'sayHi' with args: PHP
__isset()
and __unset()
__isset()
: Called when using isset()
on inaccessible propertyclass MyClass {
private $data = ['name' => 'John'];
public function __isset($name) {
return isset($this->data[$name]);
}
}
$obj = new MyClass();
var_dump(isset($obj->name)); // Output: bool(true)
__unset()
: Called when using unset()
class MyClass {
private $data = ['age' => 25];
public function __unset($name) {
unset($this->data[$name]);
}
}
$obj = new MyClass();
unset($obj->age); // Triggers __unset
__toString()
This method is called when you try to print an object using echo
or print
.
class Car {
public function __toString() {
return "This is a Car object.";
}
}
$c = new Car();
echo $c; // Output: This is a Car object.
__invoke()
When you treat an object as a function, this method is triggered.
class Greeter {
public function __invoke($name) {
echo "Hello, $name!";
}
}
$greet = new Greeter();
$greet('John'); // Output: Hello, John!
__clone()
Triggered when an object is cloned using clone
.
class Book {
public $title;
public function __clone() {
$this->title .= ' (Copy)';
}
}
$book1 = new Book();
$book1->title = "PHP Guide";
$book2 = clone $book1;
echo $book2->title; // Output: PHP Guide (Copy)
__sleep()
and __wakeup()
Used with serialize()
and unserialize()
.
__sleep()
: Before serializationclass Session {
public $user;
public function __sleep() {
return ['user'];
}
}
__wakeup()
: After unserializationclass Session {
public function __wakeup() {
echo "Session resumed!<br>";
}
}
__debugInfo()
Customize object information shown in var_dump()
.
class Person {
private $name = "John";
private $password = "secret";
public function __debugInfo() {
return [
'name' => $this->name
];
}
}
$p = new Person();
var_dump($p);
/*
Output:
object(Person)#1 (1) {
["name"]=> string(4) "John"
}
*/
__call
, __get
, etc.__get()
and __set()
to handle attributes dynamically.__debugInfo()
to show relevant info.__invoke()
for closures or service containers.__sleep()
and __wakeup()
in APIs or caching.PHP Magic Methods may sound magical, but once you understand how they work, they can be powerful tools in your object-oriented arsenal. They help you write more dynamic, flexible, and cleaner code.
But remember: with great power comes great responsibility! 😉
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google