Understanding PHP Magic Methods – A Complete Guide

Author

Kritim Yantra

May 18, 2025

Understanding PHP Magic Methods – A Complete Guide

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:

  • ✅ What magic methods are
  • ✅ Commonly used magic methods
  • ✅ When and how to use each with real examples
  • ✅ Tips and best practices

🔮 What Are Magic Methods?

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:

  • When you try to echo an object → PHP calls __toString()
  • When an object is destroyed → PHP calls __destruct()

They are defined inside a class and are not called directly. PHP triggers them behind the scenes.


🪄 List of Common PHP Magic Methods

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(): Constructor

This 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(): Destructor

This 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 methods

class 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 methods

class 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 property

class 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 serialization

class Session {
    public $user;

    public function __sleep() {
        return ['user'];
    }
}

🌅 __wakeup(): After unserialization

class 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"
}
*/

✅ Best Practices

  • Use magic methods only when necessary. Don't overuse them – they can make code hard to debug.
  • Always provide fallback logic inside __call, __get, etc.
  • Don’t suppress PHP errors silently – log them if you're using dynamic methods.
  • Avoid heavy logic inside magic methods; keep them lightweight.

🧠 Real-World Use Cases

  1. Model classes in frameworks like Laravel use __get() and __set() to handle attributes dynamically.
  2. Debugging tools use __debugInfo() to show relevant info.
  3. Custom function-like behavior using __invoke() for closures or service containers.
  4. Serialization control using __sleep() and __wakeup() in APIs or caching.

🏁 Conclusion

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! 😉

Tags

Php

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts