Magic methods

Last updated

What is Magic methods?

PHP Magic Methods, often considered the hooks of the language, provide developers a way to change how objects will respond to particular language constructs. Magic methods are special functions that start with "__" such as __construct(), __destruct(), __call(), __get(), __set() and more. They enable us to perform certain tasks automatically when specific actions occur. For example, __construct() executes when an object is created while __destruct() triggers when an object is no longer needed. Let's see the __construct magic method in action:

class Car {
    public $color;
    public function __construct($color) {
        $this->color = $color;
    }
}
$blueCar = new Car("Blue"); // This will call the __construct() method.
echo $blueCar->color;  // Outputs "Blue".

Free resources to learn Magic methods

More in stage 12: PHP-FIG

Magic methods: common questions

Can I learn Magic methods in Hindi?

This lesson is written in English. Once you sign in, open it in the interactive course and ask the AI tutor to explain Magic methods in Hindi or Hinglish. The tutor answers from this lesson’s own text, so it stays on the syllabus, and it runs on your own Google, OpenAI or Anthropic key.

Is this Magic methods tutorial for beginners?

It is lesson 88 of 120 in the free PHP roadmap, in stage 12, PHP-FIG. If you are new to PHP, start from stage 1 and come back here in order; if you already know the earlier stages, this lesson stands on its own.

Still confused? Ask me