PHP Magic Methods

Magic methods in PHP are special methods that are automatically called when certain conditions are met. These methods are named with double underscore (__) as prefix and must be declared public. They act as interceptors that provide dynamic behavior to your classes.

Object Access Magic Methods

__get() and __set()

These methods handle access to inaccessible or non-existing properties −

<?php
class User {
    private $data = [];
    
    public function __get($name) {
        return $this->data[$name] ?? null;
    }
    
    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
}

$user = new User();
$user->name = "John";
echo $user->name;
?>
John

__isset() and __unset()

These methods handle isset() and unset() calls on inaccessible properties −

<?php
class Container {
    private $data = ['name' => 'Alice'];
    
    public function __isset($name) {
        return isset($this->data[$name]);
    }
    
    public function __unset($name) {
        unset($this->data[$name]);
    }
    
    public function __get($name) {
        return $this->data[$name] ?? null;
    }
}

$obj = new Container();
var_dump(isset($obj->name));
unset($obj->name);
var_dump(isset($obj->name));
?>
bool(true)
bool(false)

String and Function Magic Methods

__toString()

Defines how an object should be converted to string −

<?php
class Product {
    private $name;
    private $price;
    
    public function __construct($name, $price) {
        $this->name = $name;
        $this->price = $price;
    }
    
    public function __toString() {
        return $this->name . " - $" . $this->price;
    }
}

$product = new Product("Laptop", 999);
echo $product;
?>
Laptop - $999

__invoke()

Allows objects to be called as functions −

<?php
class Multiplier {
    private $factor;
    
    public function __construct($factor) {
        $this->factor = $factor;
    }
    
    public function __invoke($number) {
        return $number * $this->factor;
    }
}

$double = new Multiplier(2);
echo $double(5);
?>
10

Serialization Magic Methods

__sleep() and __wakeup()

Handle object serialization and unserialization −

<?php
class Connection {
    private $link;
    private $server;
    
    public function __construct($server) {
        $this->server = $server;
        $this->link = "Connected to $server";
    }
    
    public function __sleep() {
        return ['server'];
    }
    
    public function __wakeup() {
        $this->link = "Reconnected to {$this->server}";
    }
    
    public function getLink() {
        return $this->link;
    }
}

$conn = new Connection("localhost");
$serialized = serialize($conn);
$restored = unserialize($serialized);
echo $restored->getLink();
?>
Reconnected to localhost

Debug Magic Method

__debugInfo()

Controls what properties are shown when using var_dump() −

<?php
class SecureData {
    private $username = "admin";
    private $password = "secret123";
    private $email = "admin@example.com";
    
    public function __debugInfo() {
        return [
            'username' => $this->username,
            'email' => $this->email,
            'password' => '***hidden***'
        ];
    }
}

$data = new SecureData();
var_dump($data);
?>
object(SecureData)#1 (3) {
  ["username"]=>
  string(5) "admin"
  ["email"]=>
  string(17) "admin@example.com"
  ["password"]=>
  string(12) "***hidden***"
}

Common Magic Methods Summary

Method Triggered When Purpose
__get($name) Reading inaccessible properties Property access control
__set($name, $value) Writing to inaccessible properties Property assignment control
__toString() Object converted to string String representation
__invoke() Object called as function Callable objects

Conclusion

Magic methods provide powerful ways to create dynamic and flexible PHP classes. They enable property overloading, custom string conversion, and object serialization, making your objects more intuitive and feature-rich.

Updated on: 2026-03-15T09:13:24+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements