Sobes.tech
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.