PHP and MySQL (56 Blogs) Become a Certified Professional

What are magic methods in PHP? and How to Implement them?

Published on Sep 20,2019 13.6K Views


In PHP, special functions can be defined in such a way that they can be called automatically and does not require any function call to execute the code inside these functions. This feature is available in a special method known as magic methods. In this article, we will discuss the top Magic Methods in PHP.

 

What are Magic Methods in PHP?

Methods that begin with 2 underscores(__) are generally called Magic methods in PHP. These methods names are limited to some list of PHP supported keywords that are reserved. So any function should not be defined with the name of PHP magic methods.

Magic-Methods-in-PHP

Usually, these functions should be defined by the user and there is no need to call them explicitly.

 

List of Magic Methods in PHP

  • __construct()
  • __destruct()
  • __call($fun, $arg)
  • __callStatic($fun, $arg)
  • __get($property)
  • __set($property, $value)
  • __isset($content)
  • __unset($content)
  • __sleep()
  • __wakeup()
  • __toString()
  • __invoke()
  • __set_state($array)
  • __clone()
  • __debugInfo()

 

 

  • __construct(): It is a method that gets called automatically after the creation of an object. Any number of arguments can be defined here that will be passed when objects are created.
class sample
{
	function user_def()
	{
		echo "user defined constructor";
	}
	function __construct()
	{
		echo "predefined constructor";
	}
}
$obj= new sample();
?>

construct

 

  • __destruct(): Destructor is a common feature of the object-oriented language that gets triggered as soon as there are no other references to a particular object.
<?php class sample { function __construct() { echo "Constructor initialised"." "; } function user_def() { echo "User defined function "." "; } function __destruct() { echo "after user definition, object gets destroyed automatically"." "; } } $obj= new sample(); $obj->user_def();
//check object is destroyed or not
echo is_object($obj)."
";

?>

destruct

 

  • __call($fun, $arg): This method is called when an undefined or inaccessible method is called. Which means it is Called when an undefined or inaccessible method is invoked on an object.
<?php class Sample { function user_define() { echo "This is user defined function "; } function __call($fun, $arg) { echo "function that not exists:" . $fun." "; echo "parameter list of method that does not exist:"; print_r($arg); } } $obj = new Sample(); $obj->run("teacher"); // If the method which is not existed is called within the object, then the __call() method will be called automatically.
$obj->eat("ashok", "orange");             
$obj->user_define();
?>

call-magic-methods-in-php

 

  • __callStatic($fun, $arg): This method is called when an undefined or inaccessible method is invoked in a static manner.
<?php class Sample { function user_define() { echo "This is user defined function "; } public static function __callStatic($fun, $arg) { echo "Method that does not exist:" . $fun . " "; echo "parameter list of method that does not exist:"; print_r($arg); } } $obj = new Sample(); $obj::run("Student"); // If the method does not exist is called within the object, then the __callStatic() method will be called automatically. $obj::eat("ashok", "orange"); $obj->user_define();
?>

callstatic

 

  • __get($property):  This method is used for getting values for class properties created dynamically by PHP property overloading.
<?php class Student { private $name; private $reg; function __construct($name="", $reg=1) { $this->name = $name;
        $this->reg = $reg;
    }

    public function __get($propertyName)
    {   
        if ($propertyName == "reg")
		{
            if ($this->reg>30)
			{
                return $this->reg - 10;
            } else 
			{
                return $this->$propertyName;
            }
        } 
		else 
		{
            return $this->$propertyName;
        }
    }
}
$obj = new Student("Ashok", 60);   // Instantiate the object with the Student class and assign initial values to the properties with the constructor.
echo "Name:" . $obj->name . "
";   // When the private property is accessed, the __get() method will be called automatically,so we can get the property value indirectly.
echo "reg:" . $obj->reg . "
";    // The __get() method is called automatically,and it returns different values according to the object itself.
?>

get-magic-methods-in-php

 

  • __set($property, $value):  This method is used for putting values for class properties created dynamically by PHP property overloading.
<?php class Student { private $name; private $reg; public function __construct($name="", $reg=30) { $this->name = $name;
        $this->reg = $reg;
    }

    public function __set($property, $value)
    {
        if ($property=="reg")
        {
            if ($value > 150 || $value < 0) { return; } } $this->$property = $value;
    }

    public function fun()
	{
        echo "My name is ".$this->name.",My registration number is ".$this->reg;
    }
}

$obj=new Student("Ashok", 40); //Note that the initial value will be changed by the code below.
$obj->name = "Sushma";     //The "name" property will be assigned successfully. If there is no __set() method, then the program will throw an exception.
$obj->age = 16; //The "reg" property will be assigned successfully.
$obj->reg = 160; //160 is an invalid value, so it fails to be assigned.
$obj->fun(); 
?>

set

 

  • __isset($content): This method will be called while calling isset()  or empty() for an undefined or inaccessible member. It is invoked automatically while checking whether a required overloaded property is set or not, by using the PHP isset() function.
<?php class Student { public $gender; private $name; private $reg; public function __construct($name="", $reg=30, $gender='Male') { $this->name = $name;
        $this->reg  = $reg;
        $this->gender  = $gender;
    }

    public function __isset($content)
	{
        echo "The {$content} property is private,the __isset() method is called automatically.
";
        echo  isset($this->$content);
    }
}

$obj = new Student("Ashok", 30); // Initially assigned.
echo isset($obj->gender),"
";
echo isset($obj->name),"
";
echo isset($obj->reg),"
";
?>

isset

 

  • __unset($content): This method will be called while calling reset() for an undefined or inaccessible member.
<?php class Student { public $gender; private $name; private $reg; public function __construct($name="", $reg=30, $gender='Male') { $this->name = $name;
        $this->reg  = $reg;
        $this->gender  = $gender;
    }

    
    public function __unset($content)
	{
        echo "It is called automatically when we use the unset() method outside the class.
";
        echo  isset($this->$content);
    }
}

$obj = new Student("Ashok", 30); // Initially assigned.
unset($obj->gender);
unset($obj->name);
unset($obj->reg);
?>

unset

 

  • __sleep(): This method is called first while executing serialize(). It returns the object’s property array on cleaning PHP class objects before serialization.
<?php class Student { public $gender; public $name; public $reg; public function __construct($name="", $reg=25, $gender='Male') { $this->name = $name;
        $this->reg= $reg;
        $this->gender = $gender;
    }
    public function __sleep()
	{
        echo "It is called when the serialize() method is called outside the class.
";
        $this->name = base64_encode($this->name);
        return array('name', 'reg'); // It must return a value of which the elements are the name of the properties returned.
    }
}

$obj = new Student('Ashok'); // Initially assigned.
echo serialize($obj);
echo '
';
?>

sleep

 

  • __wakeup(): This method is called while deserialization() is executed. It would reverse work to restore objects properties and resources on invoking deserialization().
<?php class Student { public $gender; public $name; public $reg; public function __construct($name="", $reg=30, $gender='Male') { $this->name = $name;
        $this->reg =$reg;
        $this->gender = $gender;
    }
    public function __sleep() 
	{
        echo "It is called when the serialize() method is called outside the class.
";
        $this->name = base64_encode($this->name);
        return array('name', 'reg'); // It must return a value of which the elements are the name of the properties returned.
    }
    public function __wakeup() 
	{
        echo "It is called when the unserialize() method is called outside the class.
";
        $this->name = 2;
        $this->gender = 'Male';
       
    }
}
$obj= new Student('Ashok'); // Initially assigned.
var_dump(serialize($obj));
var_dump(unserialize(serialize($obj)));
?>

wakeup

 

  • __toString(): This method will be called while using echo method to print an object directly. It is expected to return a string value while using class instances with PHP printing statements.
<?php class Student { public $gender; public $name; public $reg; public function __construct($name="", $reg=30, $gender='Male') { $this->name = $name;
        $this->reg  = $reg;
        $this->gender = $gender;
    }

    public function __toString()
    {
        return  'go go go';
    }
}

$obj = new Student('Ashok'); // Initially assigned.
echo $obj;
?>

tostring-magic-methods-in-php

 

  • __invoke(): This method is defined in a class that will be called while trying to call an object in a way of calling function.
<?php class Student { public $gender; public $name; public $reg; public function __construct($name="", $reg=30, $gender='Male') { $this->name = $name;
        $this->reg  = $reg;
        $this->gender  = $gender;
    }

    public function __invoke() 
	{
        echo 'This is an object';
    }

}

$obj = new Student('Ashok'); // Initially assigned.
$obj();
?>

invoke

 

  • __set_state($array): This method is called while calling var_export(). It is a static method invoked while exporting objects property array and expects such array variable as its argument.
<?php class Student { public $gender; public $name; public $reg; public function __construct($name="", $reg=30, $gender='Male') { $this->name = $name;
        $this->reg  = $reg;
        $this->gender = $gender;
    }

}
$obj = new Student('Ashok'); // Initially assigned.
var_export($obj);
?>

setstate-magic-methods-in-php

 

  • __clone(): This method is called when the object is copied.
<?php class Student { public $gender; public $name; public $reg; public function __construct($name="", $reg=30, $gender='Male') { $this->name = $name;
        $this->reg  = $reg;
        $this->gender  = $gender;
    }

    public function __clone()
    {
        echo __METHOD__."you are cloning the object.
";
    }

}

$obj = new Student('Ashok'); // Initially assigned.
$obj2 = clone $obj;

var_dump('object1:');
var_dump($obj);
echo '
';
var_dump('object2:');
var_dump($obj2);
?>

clone

 

  • __debugInfo(): This method is called by var_dump() while dumping an object to get the properties that should be shown. If the method is not defined on an object, then all public, protected and private properties will be shown.
<?php class Sample { private $prop; public function __construct($val) { $this->prop = $val;
    }

 
    public function __debugInfo() 
	{
        return [
            'propSquared' => $this->prop ** 2,
        ];
    }
}

var_dump(new Sample(22));
?>

debuginfo-magic-methods-in-php

With this, we come to ann end of this magic method in PHP article. I hope you got an idea of the various magic methods in PHP.

Check out the PHP Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

Got a question for us? Please mention it in the comments section of ”Magic Methods in PHP” and I will get back to you.

Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What are magic methods in PHP? and How to Implement them?

edureka.co