PHP Magic Methods: Complete Guide with Examples

1. Introduction

In Object-Oriented Programming (OOP), PHP provides special functions known as Magic Methods. These methods automatically execute when certain actions occur in an object.

PHP Magic Methods are predefined methods that begin with a double underscore (__). They allow developers to define special behavior for objects such as object creation, destruction, method calls, property access, and object conversion.

In simple words:

Magic methods are special functions in PHP that are automatically triggered when certain events happen in an object.

📖
Important Points:
  • Magic methods always start with double underscore (__).
  • They must be declared inside a class.
  • PHP reserves all function names starting with __ for magical functionality.
  • Developers should not create their own methods starting with __ unless they are using official PHP magic methods.

2. List of PHP Magic Methods

PHP provides several built-in magic methods.

Some commonly used magic methods include:

  • __construct()
  • __destruct()
  • __call()
  • __callStatic()
  • __get()
  • __set()
  • __isset()
  • __unset()
  • __sleep()
  • __wakeup()
  • __toString()
  • __invoke()
  • __set_state()
  • __clone()
  • __debugInfo()

Some of these methods are already explained in other topics such as constructors, destructors, and object cloning.

In this article, we will focus mainly on how magic methods work and how to use one of the common ones: __toString().

3. Syntax of Magic Method

Magic methods are defined inside a class just like normal functions, but they follow a specific predefined name.
Basic syntax:


class ClassName {
   function __magicMethodName() {
       // code
   }
}

For example:


class Test {
   function __construct() {
       echo "Object Created";
   }
}
$obj = new Test();

Here the __construct() magic method runs automatically when the object is created.

4. Example of Magic Method

Let us see a simple example using the __toString() magic method.

Example


class Student {
   public $name = "John";
   public function __toString() {
       return $this->name;
   }
}
$obj = new Student();
echo $obj;

5. Output

John

6. Explanation

Let us understand how the above code works.
First, we created a class called Student.


class Student

Inside the class, we declared a property:


public $name = "John";

Next, we defined the __toString() magic method.


public function __toString()

This method is automatically called when an object is used as a string.

For example:


echo $obj;

Normally, if we try to print an object directly, PHP would generate an error. But if the class defines the __toString() method, PHP will call that method automatically and print the returned value.

Inside the method we returned:


return $this->name;

So when we write:


echo $obj;

PHP internally calls:


$obj->__toString();

and prints the returned string.

7. Important Rules of __toString()

The __toString() magic method has some important rules.

1. Must Return a String

The method must return a string value. If it returns another type, PHP will produce an error.

Example:


return "Student Name";

2. Cannot Accept Parameters

The __toString() method does not accept any parameters.

Correct:


function __toString()

Incorrect:


function __toString($name)

3. Cannot Throw Exceptions

The __toString() method cannot throw exceptions directly. If an exception occurs inside this method, it may result in a fatal error.

4. Automatically Called

The method is automatically triggered when an object is used in a string context, such as:


echo $object;
print $object;

8. Real-World Example

Let us look at a real-world example of using __toString() in a User class.

Example


class User {

   public $name;
   public $email;

   public function __construct($name, $email) {
       $this->name = $name;
       $this->email = $email;
   }
   public function __toString() {
       return $this->name . " (" . $this->email . ")";
   }

}
$user = new User("Rahul", "rahul@example.com");
echo $user;

Output

Rahul (rahul@example.com)

Explanation

In this example:

  1. We created a class User.
  2. The class contains two properties:
    • name
    • email
  3. The constructor initializes these values.
  4. The __toString() method returns a formatted string combining name and email.

When we write:


echo $user;

PHP automatically calls the __toString() method and prints the formatted string.

This technique is useful in applications where objects need to be displayed as readable text.

9. Advantages of Magic Methods

Magic methods provide several advantages.

1. Automatic Execution

They run automatically when certain actions occur.

2. Cleaner Code

Magic methods help reduce repetitive code.

3. Flexible Object Behavior

They allow developers to customize how objects behave.

4. Better Object Management

Magic methods help manage object creation, destruction, cloning, and debugging.

10. Conclusion

PHP Magic Methods are powerful features of Object-Oriented Programming that allow developers to define special behaviors for objects.

These methods are automatically executed when specific actions occur, such as object creation, method calls, property access, cloning, and serialization.

Magic methods always begin with double underscores (__) and must be defined inside classes.

Among them, the __toString() method is commonly used to convert objects into readable string formats.

PHP Magic method – Interview Questions

Q 1: What are magic methods in PHP?
Ans: Special methods that begin with double underscores and perform specific tasks automatically.
Q 2: Name some magic methods.
Ans: __construct(), __destruct(), __get(), __set().
Q 3: When is __toString() called?
Ans: When an object is treated as a string.
Q 4: Are magic methods predefined?
Ans: Yes, they are built into PHP.
Q 5: Why are magic methods useful?
Ans: They provide advanced control over object behavior.

PHP Magic method – Objective Questions (MCQs)

Q1. Magic methods in PHP start with ______.






Q2. Which magic method is called when an object is instantiated?






Q3. Which magic method is called when invoking inaccessible methods?






Q4. __destruct() is used to ______.






Q5. Magic methods are automatically called by ______.






Related PHP Tutorials