Sobes.tech
Junior

What are the magical methods of classes you know?

sobes.tech AI

Answer from AI

Magic methods in PHP are special methods that are called automatically on certain events. They start with __ (double underscore).

Main magic methods:

  • __construct(): Called when creating a new instance of a class. Used for object initialization.
  • __destruct(): Called when an object is destroyed or the script ends. Used for resource cleanup.
  • __call(string $name, array $arguments): Called when attempting to invoke an inaccessible or non-existent method.
  • __callStatic(string $name, array $arguments): Called when attempting to invoke an inaccessible or non-existent static method.
  • __get(string $name): Called when attempting to access an inaccessible or non-existent property.
  • __set(string $name, mixed $value): Called when attempting to set a value to an inaccessible or non-existent property.
  • __isset(string $name): Called when isset() or empty() is used on an inaccessible or non-existent property.
  • __unset(string $name): Called when unset() is used on an inaccessible or non-existent property.
  • __serialize(): Called before serializing an object with serialize(). Returns an array of properties for serialization.
  • __unserialize(array $data): Called during deserialization with unserialize(). Receives an array of data to restore properties.
  • __toString(): Allows treating the object as a string. Called when attempting to output the object as a string (e.g., with echo). Must return a string.
  • __invoke(...$arguments): Allows handling the object as a function. Called when attempting to invoke the object as a function.
  • __set_state(array $properties): Called when restoring an object with var_export(). Receives an array of the object's properties.
  • __debugInfo(): Called when var_dump() is used on the object. Should return an array with debugging information.

Example of using __construct and __toString:

<?php
class MyClass {
    private $name;

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

    public function __toString(): string {
        return "Object with name: " . $this->name;
    }
}

$obj = new MyClass("Test");
echo $obj; // Calls __toString()

Example of using __get and __set:

<?php
class MyClass {
    private $data = [];

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

    public function __get(string $name): mixed {
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }
        return null; // Or throw an exception
    }
}

$obj = new MyClass();
$obj->prop1 = "Value 1"; // Calls __set()
echo $obj->prop1; // Calls __get()
What are the magical methods of classes you know? — PHP - sobes.tech