What is magic methods in PHP?

The “magic” methods are ones with special names, starting with two underscores, which denote methods which will be triggered in response to particular PHP events.
The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo() are magical in PHP classes. You used these functions names in any of our classes unless we want the magic functionality associated with them.

__construct()

The constructor is a magic method that gets invoked when the object is instantiated.

<?php
class Db{
  public function __construct($host,$username,$password,$db) {
    mysql_connect($host,$username,$password);
  }
 $db = new Db("localhost","root","12345");
}
?>

__destruct

__destruct method does the opposite of the constructor. It gets run when the object is destroyed. We can perform cleanup operations here like releasing resources,closing connection etc.

__unset

It is invoked when unset() is used on inaccessible properties.

<?php
class Student{
public var $name;
    public function __unset($name)
    {
        echo "Unsetting $name";
    }
}
$obj = new Student;
$obj->name = "John";
echo $obj->name;
//It will show the message for Unsetting John
unset($obj->name);
?>

__toString()

The __toString() method allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.

<?php
class Student{
public var $name;
public var $course;
public var $address;
    public function __toString($name)
    {
        echo "Name :-".$this->name."\nCourse:-".$this->course."\nAddress:-".$this->address;
    }
}
$obj = new Student;
$obj->name = "John";
$obj->course= "BCA";
$obj->address= "New Delhi";
echo $obj;
//It will print as the following
//Name:John
//Course:BCA
//Address:New Delhi
?>

Leave a Reply