PHP Magic Methods Explained in Depth

PHP Magic Methods Explained in Depth

Magic methods in PHP are special methods that provide a way to implement behavior that can be triggered automatically in response to specific events in a class. These methods begin with a double underscore (__) and are part of PHP's object-oriented programming (OOP) capabilities.

This blog provides a detailed explanation of PHP magic methods and their usage with examples.

What are Magic Methods?

Magic methods are predefined methods in PHP that can be overridden to change the behavior of objects when specific actions are performed on them. They are commonly used to control object initialization, string representation, method overloading, and serialization.

List of Magic Methods

1. __construct()

The __construct() method is automatically called when an object is created.

class User {
    public $name;

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

$user = new User("John");
echo $user->name; // Output: John

2. __destruct()

The __destruct() method is called when an object is destroyed or goes out of scope.

class Logger {
    public function __destruct() {
        echo "Object destroyed.";
    }
}

$logger = new Logger();
unset($logger); // Output: Object destroyed.

3. __call()

The __call() method handles calls to undefined or inaccessible methods.

class MagicCall {
    public function __call($name, $arguments) {
        echo "Method $name was called with arguments: ". implode(", ", $arguments);
    }
}

$obj = new MagicCall();
$obj->sayHello("John", "Doe"); // Output: Method sayHello was called with arguments: John, Doe

4. __callStatic()

Similar to __call() but for static methods.

class MagicStaticCall {
    public static function __callStatic($name, $arguments) {
        echo "Static method $name was called with arguments: ". implode(", ", $arguments);
    }
}

MagicStaticCall::greet("John"); // Output: Static method greet was called with arguments: John

5. __get()

The __get() method is called when attempting to access a non-existing property.

class MagicGet {
    private $data = [];

    public function __get($name) {
        return "Property $name does not exist.";
    }
}

$obj = new MagicGet();
echo $obj->name; // Output: Property name does not exist.

6. __set()

The __set() method is called when attempting to set a non-existing property.

class MagicSet {
    private $data = [];

    public function __set($name, $value) {
        $this->data[$name] = $value;
        echo "$name has been set to $value.";
    }
}

$obj = new MagicSet();
$obj->age = 30; // Output: age has been set to 30

7. __isset()

The __isset() method is triggered when using isset() or empty() on inaccessible properties.

class MagicIsset {
    private $data = [];

    public function __isset($name) {
        return isset($this->data[$name]);
    }
}

$obj = new MagicIsset();
var_dump(isset($obj->age)); // Output: bool(false)

8. __unset()

The __unset() method is called when unset() is used on an inaccessible property.

class MagicUnset {
    private $data = ["age" => 30];

    public function __unset($name) {
        unset($this->data[$name]);
        echo "$name has been unset.";
    }
}

$obj = new MagicUnset();
unset($obj->age); // Output: age has been unset.

9. __toString()

The __toString() method allows an object to be treated as a string.

class MagicToString {
    public function __toString() {
        return "This is a MagicToString object.";
    }
}

$obj = new MagicToString();
echo $obj; // Output: This is a MagicToString object.

10. __invoke()

The __invoke() method allows an object to be called as a function.

class MagicInvoke {
    public function __invoke($name) {
        echo "Hello, $name!";
    }
}

$obj = new MagicInvoke();
$obj("John"); // Output: Hello, John!

11. __sleep() and __wakeup()

  • __sleep() prepares an object for serialization.
  • __wakeup() restores an object after serialization.
class MagicSleepWakeup {
    public $name;

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

    public function __wakeup() {
        echo "Object unserialized.";
    }
}

$obj = new MagicSleepWakeup();
$obj->name = "John";
$serialized = serialize($obj);
$unserialized = unserialize($serialized); // Output: Object unserialized.

12. __clone()

The __clone() method is called when an object is cloned.

class MagicClone {
    public $name;

    public function __clone() {
        $this->name = "Cloned Object";
    }
}

$obj1 = new MagicClone();
$obj2 = clone $obj1;

echo $obj2->name; // Output: Cloned Object

Conclusion

Magic methods in PHP provide a powerful way to manage object behavior dynamically. They are especially useful for creating flexible and reusable classes, such as data mappers, ORMs, and dynamic proxies. Understanding and properly using these methods can greatly enhance your PHP programming skills.

Recent blogs
Структурные паттерны в программировании

Структурные паттерны в программировании

Порождающие паттерны в программировании

Порождающие паттерны в программировании

Генераторы и итераторы в PHP

Генераторы и итераторы в PHP

Объектно-ориентированное программирование в PHP

Объектно-ориентированное программирование в PHP

Структуры данных в PHP

Структуры данных в PHP