What are Magic Methods?
Magic methods, as the name suggests, are unique methods meant for particular purposes. These methods have a double-underscore as a prefix for all of such methods. All these magic methods are reserved, and programmers do not use these for declaring user-defined methods. We have to declare these methods as public. These methods act as inceptors and get invoked automatically when they meet specific situations.
Here are all the magic methods explained with examples and syntax:
i) __construct():
This method gets called automatically when someone creates the object of a class. In other words, whenever you are defining a __construct() method associated with a class you are creating, there will be an automated instantiation whenever a programmer creates a new object for that class
Syntax
class newClass{
function __construct(){
// Statments within this magic method
}
function functionAnother(){
// Statements
}
}
Example
<?php
class newClass{
function __construct(){
echo " This is a construct() method that will be called automatically when the class object will be created ";
}
function functionAnother(){
echo " To call this method, you have to use the class object and invoke it using that object. ";
}
}
// Both __construct() and functionTwo() are not called
$object = new newClass();
?>
Output:
This is a construct() method that will be called automatically when the class object will be created.
Here we have created a __construct() method within the class. We can see that we have only created the class object and that automatically invoked the message echoed within the __construct(). Whereas, to call the functionAnother(), we have to use the object name to invoke it. Since we haven’t invoked the other function explicitly, it is not used.
ii) __destruct():
This function has the opposite feature as that of a __construct(). Everything that we construct using the __construct() needs to destroy to save memory space. This method gets triggered when there is no other reference to the class object it applies. The __destruct() method gets called automatically when the program implicitly destroys the object.
Syntax:
class newClass{
function __destruct(){
// Statments within this magic method
}
}
$object = new newClass();
Example:
<?php
class newClass{
function __construct(){
echo " Variables created automatically when the class object gets created ";
}
public function __destruct(){
echo " It is called when the script has to shut down. " ;
// save object state as well as clean up other memory space
}
}
// Both __construct() and functionTwo() are not called
$object = new newClass();
?>
Output:
Variables created automatically when the class object gets created It is called when the script has to shut down.
Here we have created a __construct() and a __destruct() method within the class. We can see that we have only created the class object and that automatically invoked the messages echoed within the __construct() & __destruct(). Whatever was created within the __construct() will be freed up or cleared up using the __destruct() automatically when we have created the ‘object’ of the newClass in this program.
iii) __call():
PHP programmers use the __call() for creating inaccessible methods that get dynamically created when programmers perform method overloading in PHP. This method will invoke only the usual overloaded methods of PHP.
Syntax:
public __call ( string $name , array $arguments ){
// body inside __call() magic method
// normal inaccessible method invoking
}
Example:
<?php
class MethodTest{
public function __call($n, $argu){
// Note: value of $name is case sensitive.
echo "Calling the method of object '$n' "
. implode(', ', $argu) ";
}
}
$obj = new MethodTest;
$obj -> runTest('in context to the object');
?>
Output:
Calling the method of object 'runTest' in context to the object
As you can see, we have called the method runTest() using the ‘obj’ object-name with a string parameter within it. We have not defined this method anywhere within the program. This is what invoked the __call() method. The __call() method came to the rescue and helped in stopping the program abruptly.
iv) __callStatic():
PHP programmers use the __callStatic() for creating inaccessible static methods that get dynamically created when programmers accomplish static method overloading in PHP. This method will invoke only the usual overloaded static methods of PHP.
Syntax
public __callStatic (string $name , array $arguments){
// body inside __callStatic() magic method
// inaccessible static method invoking
}
Example:
<?php
class MethodTest{
public static function __callStatic($n, $argu){
// Note: value of $name is case sensitive.
echo "Calling the static method '$n'"
. implode(', ',$argu);
}
}
$obj = new MethodTest;
MethodTest::runTest ('in context to the static method');
?>
Output:
Calling the static method 'runTest' in context to the static method
As you can see, we have called the static method runTest() using the ‘obj’ object-name with a string parameter within it. We have not defined this method anywhere within the program. This is what invoked the __callStatic() method. The __callStatic() method came to the rescue and helped in stopping the program abruptly.
v) __set():
__set() is another popular magic method that gets executed when writing data is on inaccessible (private or protected) or non-enduring class properties. This method usually complements the other magic method __get(). Programmers call them whenever a program has an undefined class variable within the script. Programmers use this method to keep an extra data object for which they have not defined object properties explicitly.
Syntax:
public __set(string $name , mixed $value){
// body of the __set() magic method
}
Example:
<?php
class Employee{
private $dat = array();
public function __set($n, $val){
echo "Executing the __set() method";
$this->dat[$n] = $val;
}
}
$obj1 = new Employee();
// __set() called
$obj1->phone = '103938457';
?>
From the above code snippet, we have tried to set up our non-existent phone property. We have thus called the __set() method that takes two arguments. The first argument ($n) is the name of the property that we want to access. The second argument ($val) represents the value we are attempting to set.
vi) __get():
It is absolutely the opposite of the __set() method. This magic method is used to makes properties code in such a way that even if they don't exist, it makes them appear as if they do. __get() is invoked when programmers try to access data from any inaccessible (private or protected) object property.
Syntax:
public __get ( string $name ){
// body of the __get() magic method
}
Example:
#Code snippet showing the use of __get() in conjunction with __set():
<?php
class Employee{
private $dat = array();
public function __set($n, $val){
$this->dat[$n] = $val;
}
public function __get($n){
if (isset($this->dat[$n])){
return $this->dat[$n];
}
}
}
$obj = new Employee();
// __set() called automatically
$obj->phone = '1020357056';
// __get() called automatically
echo $obj->phone;
?>
Here, the program wants to access the inaccessible object property which is private data of the Employee class. When the __set() method is responsible for assigning values to inaccessible (here private) object properties, the __get() is used to display that inaccessible object property.
vii) __isset():
__isset() is another magic method that the programmers use when they want to check the access of any non-existent or inaccessible properties of a class object. To call the __isset() magic method, we have to call the __isset() with the inaccessible or non-defined properties as its parameter. It is automatically invoked to check whether a needed object property is set or not.
Syntax:
public __isset ( string $name ){
// body of the __isset() magic method
}
Example:
<?php
class Manager{
private $dat = array();
public function __isset($n){
echo "__isset() magic method invoked.";
return isset($this->dat[$n]);
}
}
$obj2 = new Manager();
echo isset($obj2->empid);
?>
Output:
__isset() magic method invoked.
Here, the program wants to access the inaccessible object property which is not defined as a part of the Manager class. The isset() method takes the ‘empid’ inaccessible variable as a parameter for checking the existence of the object property.
viii) __unset():
__unset() is another magic method that is invoked automatically for destroying a variable and freeing up memory space. When __isset() is used for checking whether a variable exists or not, the __unset() simply destroys a variable when used on non-existing or inaccessible properties.
Syntax:
public __unset(string $name ){
// body of the __unset() magic method
}
Example:
<?php
class Manager{
private $dat = array();
public function __isset($n){
return isset($this->dat[$n]);
}
public function __unset($n){
echo "__unset() magic method invoked.";
unset($this->dat[$n]);
}
}
$obj2 = new Manager();
$obj2->a = 62;
if (isset($obj2->a))
unset($obj2->a);
echo "Destroyed obj2 -> a ";
?>
Output:
Destroyed obj2 -> a
Here, the program checks whether the non-existing variable exists or not. The __isset() will check its existence. If it exists, the unset will destroy the variable and free up memory space using the __unset() method.
ix) __sleep() and __wakeup():
__sleep()
When the object gets serialized, programmers use the __sleep() method. In other words, this method comes into the picture when we use the serialize() method. In case you have a very large object, you only wish to keep selected properties throughout serialization - you can use __sleep(). It must return an array having the names of all object properties that we want to serialize.
Syntax:
public function __sleep(){
// return array();
}
Example:
<?php
class Employee {
public $name; public $regn; public $gender;
public function __construct($name = "", $regn = 628, $gender = 'Male'){
$this->name = $name;
$this->regn= $regn;
$this->gender = $gender;
}
public function __sleep(){
echo "__sleep() will be called if the serialize() method is used outside the class.";
$this->name = base64_encode ($this->name);
return array('name', 'regn');
}
}
$obj1 = new Employee('Karlos'); // Assigned a value initially
echo serialize($obj1);
?>
Output:
__sleep() will be called if the serialize() method is used outside the class. O:8:"Employee":2:{s:4:"name";s:8:"S2FybG9z";s:4:"regn";i:628;}
In this program, the __construct() to automatically assign $name, $regn, and $gender. Within the __sleep() method, we returned the array, having the names of all object properties that we want to serialize. Now, from outside the class, we have called the serialize() function by passing the class object as the parameter. It automatically invoked the __sleep() method for extracting all object properties that we want to serialize.
__wakeup():
The magic method helps to re-establish any connections and start-up tasks when programmers invoke the unserialize() function with the class object. This method gets invoked automatically when the deserialization takes place.
Example:
<?php
class Employee{
public $name; public $regn; public $gender;
public function __construct($name = "", $regn = 628, $gender = 'Male'){
$this->name = $name;
$this->regn= $regn;
$this->gender = $gender;
}
public function __wakeup(){
echo "__wakeup() will be called if the unserialize() method is called outside the class.";
$this->gender = 'Male';
}
}
$obj1 = new Employee('Karlos'); // Initially assigned.
var_dump(unserialize(serialize($obj1)));
?>
__wakeup() will be called if the unserialize() method is called outside the class.object(Employee)#2 (3) { ["name"]=> string(6) "Karlos" ["regn"]=> int(628) ["gender"]=> string(4) "Male" }
xi) __toString():
This magic method allows determining if you'd like to show or treat any class object as a string. It returns a string value when we use the class instances with PHP. If the programmer specifies any return type other than string, it will show an error like this:
“Fatal error: Method TestClass ::__toString() must return a string value”
Syntax:
public function __toString(){
// return strings and string values
}
Example:
<?php
class Employee {
private $n;
private $mail;
public function __construct($n, $mail){
$this->n = $n;
$this->mail = $mail;
}
public function __toString(){
return 'Name of the Employee: '.$this -> n
. '<br>Email ID is: '.$this->mail;
}
}
$obj2 = new Employee('Karlos', 'Karliris@gmail.com');
echo $obj2;
?>
Output:
Name of the Employee:Karlos
Email ID is:Karliris@gmail.com
In this program __construct() is invoked automatically when the object is created for the Employee class. Now to treat any class object as a string, we have used here the __toString() method where we have passed the employee name and email as string values. Now, echoing the class object echo $obj2; will display the value given within the __toString().
xii) __invoke():
It is another essential utility magic method that is automatically called when programmers try to invoke an object as if it is a general function. In other words, when we try to make a function call using the class object name, the __invoke() method executes itself.
Syntax:
public function __invoke(){
// body of the __invoke() when for displaying some value when object called as function.
}
Example:
<?php
class Employee {
private $n;
private $mail;
public function __construct($n, $mail){
$this->n = $n;
$this->mail = $mail;
}
public function __invoke(){
echo 'Employee object when called as a function, invokes this method for displaying some value';
}
}
$obj3 = new Employee('Karlos','karliris@gmail.com');
// class instance used as function call
$obj3();
?>
Output:
Employee object when called as a function, invokes this method for displaying some value
In this __construct() invoked automatically when the object is created for the Employee class. Now, the object of the class is created and the object is called a normal function call. As soon as PHP encounters such a situation, $obj3(); it will automatically call the __invoke().
xiii) __set_state():
This is a static magic method that is used with the var_export() function. As we all know that the var_export() function will provide or return a piece of structured information about any variable or class instance passed within it. When PHP programmers use the var_export() function for exporting classes, they use the __set_state() method.
Syntax:
public static function __set_state(array){
// body of the __set_state()
}
Example:
<?php
class Employee {
public $ename;
private $mail;
public function __construct($ename, $mail){
$this->ename = $ename;
$this->mail = $mail;
}
public static function __set_state(array $array){
$obj = new Student;
$obj->ename = $array['ename'];
$obj->mail = $array['mail'];
return $obj;
}
}
$obj4 = new Employee('Ray', 'ray@stechies.com');
var_export($obj4);
?>
Output:
Employee::__set_state(array( 'ename' => 'Ray', 'mail' => 'ray@stechies.com', ))
__construct() gets invoked automatically when the object is created for the Employee class. The static __set_state() method takes the array as a parameter and returns the object. Now, we have created the class object outside the class by providing two string arguments (employee name and email ID). As soon as PHP encounters the var_export() function where the object ($obj4) is passed as parameter, it will invoke the __set_state() method.
xiv) __clone():
As we all know, we use the clone keyword to duplicate any existing object. But what if we wish to modify the properties of the duplicate object. To do this, we have to use the __clone() from within the class where we can perform the modification of the duplicate object.
Syntax:
public function __clone(){
// body of the __clone()
}
Example:
<?php
class Employee_Dept{
# another dummy class
}
class Employee{
private $email;
private $object_emp_dept;
public function __construct(){
$this->object_emp_dept = new Employee_Dept();
}
public function __clone(){
echo " __clone() method invoked. ";
$this->object_emp_dept = clone $this->object_emp_dept;
}
}
$objone = new Employee();
$objtwo = clone $objone;
?>
In this program, we have created two classes. Emplyee_Dept {} class is left empty to show how this program works. The Employee class has a __construct() that is invoked automatically when the object is created for the Employee class. The cloning of the object is done within the __construct(). Within the __clone() method, we are performing the modification of the duplicate object. Outside the class, $objtwo = clone $objone; perform the duplication using assignment operator.
xv) __debugInfo():
It is another utility magic method that is called automatically when we want to dump any object with the help of the var_dump() function. In case this method is not defined as associating an object, then it dumps all public, protected, and private properties of that class.
Syntax:
public function __debugInfo() {
// body and return statement of the __debugInfo() method
}
Example:
<?php
class Employee{
public $n;
private $email;
private $eno;
public function __debugInfo(){
return array('Employee_Name'=>$this->n);
}
}
$obj4=new Employee();
var_dump($obj4);
?>
Output:
object(Employee)#1 (1) { ["Employee_Name"]=> NULL }