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 whenisset()orempty()is used on an inaccessible or non-existent property.__unset(string $name): Called whenunset()is used on an inaccessible or non-existent property.__serialize(): Called before serializing an object withserialize(). Returns an array of properties for serialization.__unserialize(array $data): Called during deserialization withunserialize(). 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., withecho). 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 withvar_export(). Receives an array of the object's properties.__debugInfo(): Called whenvar_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()