Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔴 Advanced  ·  Lesson 25

Magic Methods in PHP

In this lesson: Learn PHP magic methods — __construct, __destruct, __get, __set, __call, __toString — with examples and output.

What are magic methods

Magic methods are special methods whose names begin with two underscores, like __construct or __toString. You never call them by name — PHP calls them automatically at the right moment, such as when an object is created, read, or printed. They let a class hook into these events.

💡 The double underscore __ marks a method as magic — auto-called by PHP, not by you.

__construct and __destruct

__construct runs when an object is created; __destruct runs when it is destroyed.

<?php
  class User {
      public function __construct() {
          echo "Object created\n";
      }
      public function __destruct() {
          echo "Object destroyed";
      }
  }
  $u = new User();
?>
Object created
Object destroyed

__construct is by far the most used magic method — it sets up new objects. __destruct runs at cleanup time, useful for closing resources.

__get and __set

These run when you access a property that is not directly available.

<?php
  class Box {
      private $data = [];
      public function __set($name, $value) { $this->data[$name] = $value; }
      public function __get($name) { return $this->data[$name] ?? null; }
  }
  $b = new Box();
  $b->color = "red";     // calls __set
  echo $b->color;        // calls __get
?>
red

Even though color is not a declared property, __set and __get intercept the access, letting the class manage it — great for validation or storing data flexibly.

__call

__call runs when you call a method that does not exist.

<?php
  class Api {
      public function __call($name, $args) {
          return "You called $name";
      }
  }
  $a = new Api();
  echo $a->anything();
?>
You called anything

Instead of an error, __call catches the missing method — handy for building flexible APIs or forwarding calls elsewhere.

__toString

__toString decides what an object looks like when used as text.

<?php
  class Money {
      public $amount = 100;
      public function __toString() {
          return "Rs " . $this->amount;
      }
  }
  echo new Money();
?>
Rs 100

Without __toString, echoing an object causes an error. With it, you control the string representation — perfect for objects that have a natural text form.

Common mistakes

  • Calling magic methods directly. You rarely write $obj->__construct() — PHP calls them for you.
  • Forgetting __toString returns a string. It must return text, not echo it.
  • Overusing __get/__set. They can hide bugs; declare real properties when you can.
  • One underscore instead of two. Magic methods need the double underscore __.

Summary

  • Magic methods start with __ and are called automatically by PHP.
  • __construct/__destruct run at object creation and cleanup.
  • __get/__set intercept property access.
  • __call catches calls to missing methods.
  • __toString defines an object's text form for echo.

Next, structure classes with PHP OOP, or reuse code with PHP traits.

Frequently Asked Questions

What are magic methods in PHP?
Magic methods are special methods whose names start with two underscores (like __construct). You do not call them directly — PHP calls them automatically at certain moments, such as when an object is created or turned into a string.
What does __construct do?
__construct() runs automatically the moment you create an object with new. It is used to set up the object's starting values. It is the most commonly used magic method.
What are __get and __set for?
__get runs when you read a property that is not accessible or does not exist, and __set runs when you write to one. They let a class control or intercept property access, useful for validation or virtual properties.
What does __toString do?
__toString() defines what happens when an object is used as a string, for example with echo $obj. Without it, echoing an object causes an error; with it, you decide the text representation.
Why are they called magic methods?
Because they are triggered automatically "behind the scenes" by PHP, rather than being called by name in your code. The double underscore prefix marks them as these special, auto-invoked methods.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicPDO vs MySQLi Your progress: 25 / 50 (50%) · Lesson 26 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free