PHP Magic Methods Explained with Examples

In PHP, magic methods are special, predefined methods that are automatically triggered in response to specific actions performed on an object. This article provides a clear overview of what PHP magic methods are, explains how they function behind the scenes, and explores practical examples of commonly used magic methods like __construct, __toString, __get, and __set to help you write cleaner, more dynamic object-oriented code.

What Are Magic Methods?

Magic methods in PHP are reserved methods that allow you to react to specific events during an object’s lifecycle. They always begin with a double underscore (__). PHP reserves all method names starting with __ for this purpose, so you should not create custom methods with this prefix unless you are hooking into PHP’s built-in magic functionality.

These methods enable features like property overloading, method overloading, database serialization, and automatic object initialization.


Common Examples of PHP Magic Methods

1. __construct()

The constructor is the most frequently used magic method. It is automatically called when a new instance of a class is created. It is typically used to initialize object properties or run setup tasks.

class User {
    public $username;

    public function __construct($name) {
        $this->username = $name;
    }
}

// Automatically triggers __construct()
$user = new User("Alice");
echo $user->username; // Outputs: Alice

2. __toString()

The __toString() method is triggered when an object is treated as a string, such as when you attempt to print or echo the object directly. It must return a string value.

class Book {
    private $title;

    public function __construct($title) {
        $this->title = $title;
    }

    public function __toString() {
        return "Book Title: " . $this->title;
    }
}

$book = new Book("The Great Gatsby");
// Automatically triggers __toString()
echo $book; // Outputs: Book Title: The Great Gatsby

3. __get() and __set()

These methods are used for property overloading. * __get($name) is called when you attempt to read data from inaccessible (private or protected) or non-existent properties. * __set($name, $value) is run when writing data to inaccessible or non-existent properties.

class Product {
    private $data = [];

    // Triggered when writing to an inaccessible property
    public function __set($name, $value) {
        $this->data[$name] = $value;
    }

    // Triggered when reading an inaccessible property
    public function __get($name) {
        return $this->data[$name] ?? "Property not found";
    }
}

$product = new Product();
$product->price = 19.99; // Calls __set('price', 19.99)

echo $product->price;    // Calls __get('price'), Outputs: 19.99
echo $product->title;    // Calls __get('title'), Outputs: Property not found

4. __call()

The __call($name, $arguments) method is triggered when you attempt to invoke an inaccessible or non-existent method in an object context. It is highly useful for creating dynamic API wrappers or forwarding method calls.

class Logger {
    public function __call($name, $arguments) {
        echo "The method '$name' was called with arguments: " . implode(', ', $arguments);
    }
}

$logger = new Logger();
// Automatically triggers __call() because 'logError' does not exist
$logger->logError("Database connection failed", 500); 
// Outputs: The method 'logError' was called with arguments: Database connection failed, 500