Junior — Middle
Can you give examples of magic methods used in classes?
sobes.tech AI
Answer from AI
In PHP, magic methods are special methods that start with a double underscore __ and are called automatically in certain situations. Here are some examples:
__construct()— called when creating an object (constructor).__destruct()— called when destroying an object.__get($name)— called when attempting to access a non-existent or inaccessible property.__set($name, $value)— called when assigning a value to a non-existent or inaccessible property.__call($name, $arguments)— called when calling a non-existent or inaccessible method.__toString()— called when attempting to convert an object to a string.
Example of usage:
class User {
private $data = [];
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
return $this->data[$name] ?? null;
}
public function __toString() {
return "User: " . ($this->data['name'] ?? 'unknown');
}
}
$user = new User();
$user->name = "Ivan";
echo $user; // Will output: User: Ivan