Table of contents
1.
Introduction
2.
Method Names, Return Types, and Conditions of Calling
3.
__construct() Method
3.1.
Purpose
3.2.
Syntax
3.3.
Example
4.
__destruct() Method
4.1.
Purpose
4.2.
Syntax
4.3.
Example
5.
__call($name, $parameters) Method
5.1.
Purpose
5.2.
Syntax
5.3.
Example
6.
__toString() Method
6.1.
Purpose
6.2.
Syntax
6.3.
Example
7.
__get($name) Method
7.1.
Purpose
7.2.
Syntax
7.3.
Example
8.
__set($name, $value) Method
8.1.
Purpose
8.2.
Syntax
8.3.
Example
9.
__debugInfo() Method
9.1.
Purpose
9.2.
Syntax
9.3.
Example
10.
__invoke() Method
10.1.
Purpose
10.2.
Syntax
10.3.
Example
11.
__clone() Method
11.1.
Purpose
11.2.
Syntax
11.3.
Example
12.
Frequently Asked Questions
12.1.
What are PHP magic methods? 
12.2.
Why is __construct() important? 
12.3.
Can magic methods improve debugging? 
13.
Conclusion
Last Updated: Jan 25, 2025
Easy

What are PHP Magic Methods

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

PHP Magic Methods are special methods in PHP that are automatically called when certain events occur within a class. These methods allow developers to perform tasks like handling object initialization, method overloading, property access, and object destruction in an intuitive and efficient way. Magic methods in PHP are prefixed with two underscores (__), signaling that they are reserved for specific internal operations.

What are PHP Magic Methods

In this article, you will learn about the most commonly used PHP magic methods, including __construct, __destruct, __get, __set, and others. We will learn about its syntax, use cases, and how to leverage them to enhance your PHP applications. Understanding PHP magic methods will allow you to write cleaner, more dynamic, and easier-to-maintain code.

Method Names, Return Types, and Conditions of Calling

Below are PHP magic methods that are commonly used in PHP applications. 

  • __construct(): Called when an object is created.
     
  • __destruct(): Called when an object is destroyed.
     
  • __call($name, $parameters): Handles calls to inaccessible or undefined methods.
     
  • __toString(): Defines how an object is converted to a string.
     
  • __get($name): Called when reading data from inaccessible properties.
     
  • __set($name, $value): Called when writing data to inaccessible properties.
     
  • __debugInfo(): Specifies what information is shown during debugging.
     
  • __invoke(): Called when an object is used as a function.
     
  • __clone(): Called when an object is cloned.

__construct() Method

Purpose

The __construct() method initializes an object when it is created.

Syntax

public function __construct([parameters]) {
    // Initialization code
}

Example

class Person {
    public $name;

   public function __construct($name) {
        $this->name = $name;
    }
}

$person = new Person("John");
echo $person->name; 
You can also try this code with Online PHP Compiler
Run Code

 

Output

John

 

Explanation

The constructor is automatically called when the object is instantiated, setting up the $name property in the example.

__destruct() Method

Purpose

The __destruct() method is called when an object is no longer needed.

Syntax

public function __destruct() {
    // Cleanup code
}

Example

class FileHandler {
    public $file;

    public function __construct($filename) {
        $this->file = fopen($filename, 'w');
    }

    public function __destruct() {
        fclose($this->file);
        echo "File closed.";
    }
}

$fileHandler = new FileHandler("example.txt");
You can also try this code with Online PHP Compiler
Run Code


Explanation

The __destruct() method is invoked when the object goes out of scope or is explicitly destroyed.

__call($name, $parameters) Method

Purpose

Handles calls to inaccessible or undefined methods in a class.

Syntax

public function __call($name, $parameters) {
    // Handle method call
}

Example

class MagicMethod {
    public function __call($name, $parameters) {
        echo "Method '$name' called with arguments: ". implode(", ", $parameters);
    }
}
$obj = new MagicMethod();
$obj->undefinedMethod("arg1", "arg2");
You can also try this code with Online PHP Compiler
Run Code


Output: 

Method 'undefinedMethod' called with arguments: arg1, arg2


Explanation

This method captures calls to methods that do not exist and provides a fallback mechanism.

__toString() Method

Purpose

Specifies how an object is converted to a string.

Syntax

public function __toString() {
    return "string representation";
}

Example

class Book {
    public $title;
    public function __construct($title) {
        $this->title = $title;
    }
    public function __toString() {
        return "Book title: " . $this->title;
    }
}
$book = new Book("PHP Programming");
echo $book; 
You can also try this code with Online PHP Compiler
Run Code


Output: 

Book title: PHP Programming

__get($name) Method

Purpose

Handles reading data from inaccessible or non-existent properties.

Syntax

public function __get($name) {
    // Retrieve property value
}

Example

class MagicProperty {
    private $data = ["name" => "Alice"];

    public function __get($name) {
        return $this->data[$name] ?? "Property not found";
    }
}

$obj = new MagicProperty();
echo $obj->name; 
You can also try this code with Online PHP Compiler
Run Code


Output:

Alice

__set($name, $value) Method

Purpose

Handles writing data to inaccessible or non-existent properties.

Syntax

public function __set($name, $value) {
    // Set property value
}

Example

class MagicProperty {
    private $data = [];
    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
    public function __get($name) {
        return $this->data[$name] ?? "Property not found";
    }
}

$obj = new MagicProperty();
$obj->age = 25;
echo $obj->age; 
You can also try this code with Online PHP Compiler
Run Code


Output: 

25

__debugInfo() Method

Purpose

Controls the output of var_dump() for an object.

Syntax

public function __debugInfo() {
    return ["property" => "value"];
}

Example

class Debuggable {
    private $secret = "Hidden";
    public function __debugInfo() {
        return ["visible" => "Debug info here"];
    }
}
$obj = new Debuggable();
var_dump($obj);
You can also try this code with Online PHP Compiler
Run Code

 

Output: 

array(1) { ["visible"]=> string(14) "Debug info here" }

__invoke() Method

Purpose

Allows an object to be called as a function.

Syntax

public function __invoke([parameters]) {
    // Code to execute
}

Example

class CallableClass {
    public function __invoke($param) {
        return "You called the object with: $param";
    }
}
$obj = new CallableClass();
echo $obj("some data"); 
You can also try this code with Online PHP Compiler
Run Code


Output: 

You called the object with: some data

__clone() Method

Purpose

Defines behavior when an object is cloned.

Syntax

public function __clone() {
    // Code to execute during cloning
}

Example

class Clonable {
    public $data;
   public function __construct($data) {
        $this->data = $data;
    }

    public function __clone() {
        $this->data = "Cloned: " . $this->data;
    }
}
$obj1 = new Clonable("Original");
$obj2 = clone $obj1;
echo $obj2->data; 
You can also try this code with Online PHP Compiler
Run Code


Output: 

Cloned: Original

Frequently Asked Questions

What are PHP magic methods? 

PHP magic methods are special methods with double underscores that define specific behaviors for objects in certain situations.

Why is __construct() important? 

It initializes an object when it is created, setting up necessary properties or dependencies.

Can magic methods improve debugging? 

Yes, the __debugInfo() method customizes what information is displayed during debugging, making it more relevant.

Conclusion

PHP Magic methods provide a powerful way to control the behavior of objects. They enhance flexibility by allowing you to customize object construction, destruction, method handling, and property access. Understanding these methods can significantly improve your object-oriented programming skills.

Live masterclass