What are Magic Methods in PHP and their Purpose

Reading Time: 10 minutes
782 Views

Inside this article we will see the concept i.e What are Magic Methods in PHP and their Purpose Tutorial. Article contains the classified information i.e What are magic methods and how to use them in PHP.

In PHP, “magic methods” are special methods that begin with two underscores (e.g. __construct, __destruct). They are used to define certain behaviors of a class, such as how it should be constructed or how it should be represented as a string.

Read More: What are Access Modifiers in PHP Tutorial Example

Let’s get started.

Characteristics of PHP Magic Methods

Some characteristics of magic methods in PHP include:

  1. They are prefixed with double underscores (e.g. __construct, __destruct).
  2. They are used to define certain behaviors of a class, such as how it should be constructed or how it should be represented as a string.
  3. They are automatically called by the PHP runtime, based on specific events or actions.
  4. They can’t be called directly.
  5. Some of them are used as a special getter/setter.
  6. They can be overridden in child classes.
  7. They can be used to customize the behavior of a class when certain conditions are met, such as when an object is cloned, when an object is destroyed, or when an object is used as a string.
  8. They are not necessary to use in a class, but they can provide additional functionality and flexibility.

It’s important to note that magic methods should generally be used sparingly, as they can make code more difficult to understand and debug.

PHP Magic Methods

Some examples of magic methods in PHP include:

  • __construct(): called when an object is created
  • __destruct(): called when an object is destroyed
  • __call(): called when a method that doesn’t exist is called on an object
  • __get(): called when an inaccessible property is read
  • __set(): called when an inaccessible property is written to
  • __toString(): called when an object is used as a string
  • __clone(): called when an object is cloned

Read More: Top Javascript Frameworks in 2023 For Developers To Learn

Usage of Magic Methods of PHP

The following are code snippets and examples to understand magic methods better.

__construct()

__construct() is a magic method in PHP that is automatically called when an object of a class is created. It is used to initialize the object’s properties and set up any necessary resources or connections. The __construct() method takes no parameters by default, but it can accept any number of parameters if needed.

Here’s an example of how __construct() might be used in a class:

<?php
  
class MyClass {
    private $property;

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

    public function getProperty() {
        return $this->property;
    }
}

$obj = new MyClass("Hello World!");
echo $obj->getProperty(); // Outputs "Hello World!"

__destruct()

__destruct() is a magic method in PHP that is automatically called when an object of a class is destroyed. It is used to clean up any resources or connections that were set up in the class’s __construct() method. The __destruct() method takes no parameters and does not return a value.

Here’s an example of how __destruct() might be used in a class:

<?php
  
class MyClass {
    private $connection;

    public function __construct() {
        $this->connection = new PDO("mysql:host=localhost;dbname=mydb", "user", "password");
    }

    public function __destruct() {
        $this->connection = null;
    }
}

In this example, the __construct() method sets up a new connection to a MySQL database using the PDO class. The __destruct() method then closes the connection by setting the $connection property to null.

Read More: Do You Know Top PHP Frameworks in 2023 for Web Developers

__call()

__call() is a magic method in PHP that is automatically called when an inaccessible method is called on an object of a class. It is used to handle calls to undefined methods in an object-oriented context. The __call() method takes two parameters: the name of the method that was called, and an array of arguments passed to the method.

Here’s an example of how __call() might be used in a class:

<?php

class MyClass {
    public function __call($name, $arguments) {
        echo "Call to undefined method " . $name . " with arguments " . implode(', ', $arguments) . "\n";
    }
}

$obj = new MyClass();
$obj->undefinedMethod("hello", "world");

In this example, the __call() method is defined in the MyClass class. When an undefined method is called on an object of the MyClass class, the __call() method is automatically called. In this case, the call to $obj->undefinedMethod("hello", "world") would result in the output "Call to undefined method undefinedMethod with arguments hello, world".

__get()

__get() is a magic method in PHP that is automatically called when an inaccessible property is accessed on an object of a class. It is used to handle requests for non-existent or private properties in an object-oriented context. The __get() method takes one parameter: the name of the property that was accessed.

Here’s an example of how __get() might be used in a class:

<?php
  
class MyClass {
    private $property;

    public function __get($name) {
        if ($name == "property") {
            return $this->property;
        } else {
            return "No such property!";
        }
    }

    public function __set($name, $value) {
        if ($name == "property") {
            $this->property = $value;
        }
    }
}

$obj = new MyClass();
$obj->property = "Hello World!";
echo $obj->property; // Outputs "Hello World!"

In this example, the __get() method is defined in the MyClass class. When an inaccessible property is accessed on an object of the MyClass class, the __get() method is automatically called. In this case, the call to $obj->property would result in the output "Hello World!".

Read More: Laravel Migration Add Column After Specific Column Tutorial

__set()

__set() is a magic method in PHP that is automatically called when an inaccessible property is set on an object of a class. It is used to handle requests to set the value of non-existent or private properties in an object-oriented context. The __set() method takes two parameters: the name of the property that is being set and the value that is being assigned to it.

Here’s an example of how __set() might be used in a class:

<?php
  
class MyClass {
    private $property;

    public function __set($name, $value) {
        if ($name == "property") {
            $this->property = $value;
        }
    }
    public function __get($name) {
        if ($name == "property") {
            return $this->property;
        }
    }
}

$obj = new MyClass();
$obj->property = "Hello World!";
echo $obj->property; // Outputs "Hello World!"

In this example, the __set() method is defined in the MyClass class. When an inaccessible property is set on an object of the MyClass class, the __set() method is automatically called. In this case, the call to $obj->property = "Hello World!" would result in the property property of the object being set to the value “Hello World!”.

We hope this article helped you to learn about i.e What are Magic Methods in PHP and their Purpose Tutorial Example in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more