What are PHP magic methods

PHP magic methods are special methods that allow you to control the behavior of objects in PHP. These methods are automatically called in response to specific actions, enabling you to customize object behavior without directly calling a method. Some of the most common magic methods include:

  • __construct() - Called when an object is created.
  • __destruct() - Called when an object is destroyed.
  • __get() - Called when accessing an inaccessible property.
  • __set() - Called when setting an inaccessible property.
  • __call() - Called when invoking inaccessible methods.
  • __invoke() - Called when an object is treated as a function.
  • __toString() - Called when an object is treated as a string.

These methods provide a powerful way to manage object interactions, enforce encapsulation, and create more dynamic and flexible classes in PHP. Below is an example of how to use some of these magic methods:


class MagicExample {
    private $data = [];

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

    public function __get($name) {
        return $this->data[$name] ?? null;
    }

    public function __set($name, $value) {
        $this->data[$name] = $value;
    }

    public function __toString() {
        return implode(', ', $this->data);
    }
}

$example = new MagicExample(['name' => 'John', 'age' => 30]);
echo $example->name; // Output: John
$example->city = 'New York';
echo $example; // Output: John, 30, New York
    

PHP magic methods __construct __get __set __call __invoke __toString