Junior — Middle
Have you had experience using special methods starting with double underscores in PHP?
sobes.tech AI
Answer from AI
In PHP, special methods starting with double underscores (__) are called magic methods. They allow overriding the behavior of objects in certain situations. For example:
__construct()— class constructor__destruct()— destructor__get($name)— called when accessing a non-existent or inaccessible property__set($name, $value)— called when writing to a non-existent or inaccessible property__call($name, $arguments)— called when invoking a non-existent method__toString()— defines the behavior of the object when converted to a string
Example of using __get and __set:
class User {
private $data = [];
public function __get($name) {
return $this->data[$name] ?? null;
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
}
$user = new User();
$user->name = 'Ivan';
echo $user->name; // Will output 'Ivan'
Magic methods allow flexible management of object behavior and are often used to implement design patterns or simplify class interfaces.