Sobes.tech
Junior — Middle

Could you explain what is meant by 'magic functions' in programming?

sobes.tech AI

Answer from AI

In PHP, "magic methods" refer to special methods whose names start and end with a double underscore (__). They are automatically invoked by the interpreter in certain situations, allowing to alter the behavior of objects.

Examples of magic methods:

  • __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 how an object is 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;  // Ivan

Thus, magic methods allow flexible management of object behavior and simplify working with objects in certain scenarios.

Could you explain what is meant by 'magic functions'… - sobes.tech