Flipkart

Friday, June 11, 2010

Magic Methods in PHP

With PHP 5 Object Oriented Programming seems to becoming a reality in PHP but we all know that in PHP a variable can take any form depending on the data passed to it. Also PHP automatically creates variable and assigns values to it even is the variables are not defined. But in Object Oriented Programming all the data members/methods needs to be defined. To solve some of these problems in OOPS environment magic methods have been introduced in PHP5.

NOTE ON MAGIC METHODS:
  • Magic methods are the members functions that is available to all the instance of class
  • Magic methods always starts with “__”. Eg. __construct
  • All magic methods needs to be declared as public
  • To use magic method they should be defined within the class or program scope
Various Magic Methods used in PHP 5 are:
  • __construct()
  • __destruct()
  • __set()
  • __get()
  • __call()
  • __toString()
  • __sleep()
  • __wakeup()
  • __isset()
  • __unset()
  • __autoload()
  • __clone()


__construct()
Constructor are special function in Object Oriented Programming. It gets called automatically whenever object of a class is created. This is useful for performing any pre operation before we start to call the methods of the class. PHP5 uses special keyword “__construct” to define constructor of the class.

< ?
class employee
{
    function __construct()
   {
       echo "Constructor Called";
   } 
}
$a = new employee();
$a = new employee;
? >


__destruct()
Destructor are special function in Object Oriented Programming. It gets called automatically whenever object of a class is destroyed or goes out of scope. This is useful for clean up operation before cleaning the memory. PHP 5 uses special keyword “__destruct” to define destructor of the class.

< ?
class employee
{
    function __destruct()
    {
        echo "Destructor Called";
    }
}
$a = new employee();
? >
 
 So when the page operation is completed destructor function is called automatically.
__set()
This tutorial will guide you through the __set() Magic Method. The __set() Magic method in PHP5 gets called when setting the value to an undeclared or undefined attributes of an class. With this method the programmer can keep track on the variables which are not defined inside the class.

< ?
class magicmethod
{
 function __set($data,$value)
 {
  echo "Error assigning values to undefined attributes";
  echo "attributes Called:".$data;
  echo "Value assigned to attributes:".$value;
 }
 
}
$a = new magicmethod();
$a->setData = 20;
? >
 
Output:

Error assigning values to undefined attributes

attributes Called:setData

Value assigned to attributes:20 

__get()
This tutorial will guide you through the __get() Magic Method. The __get Magic method in PHP5 gets called when accessing the value of an undeclared or undefined attribute of an class. With this method the programmer can keep track on the variables which are not defined inside the class.

< ?
class magicmethod
{
   function __get($data)
   {
       echo "Error accessing undefined attributes";
       echo "attributes Called:".$data;
   }
}
 
$a = new magicmethod();
echo $a->setData;
 
? >
 
Output:

Error accessing undefined attributes

attributes Called:setData 

__call()
This tutorial will guide you through the __call() Magic Method. The __call Magic method in PHP5 get called when accessing an undeclared or undefined methods of an class. With this magic method the programmer can keep track on the undeclared method which are not defined inside the class.

< ?
class magicmethod
{
 
 function __call($data,$argument)
 {
  echo "Error accessing undefined Method";
  echo "Method Called: ".$data;
  echo "Argument passed to the Method: ".$argument;
 }
 
}
 
$a = new magicmethod();
echo $a->setData();  //Calling setData method
 
? >
 
Output:

Error accessing undefined Method

Method Called: setData

Argument passed to the Method: Array (Array of the Argument Passed) 

__toString()
This tutorial will guide you through the __toString() Magic Method. The __toString() Magic method in PHP5 get called while trying to print or echo the class objects. This method can be used print all the methods and attributes defined for the class at runtime for debugging. Also this method can be used to give error message while somebody tries to print the class details.

< ?
class magicmethod
{
 
 function __toString()
 {
  return "Caught You!! Cannot access the Class Object";
 }
 
}
$a = new magicmethod();
echo $a;
? >

Output: Caught You!! Cannot access the Class Object

__sleep()
This tutorial will guide you through the __sleep() Magic Method. The __sleep() magic method in PHP5 gets called while serializing an object in PHP5. Serializing is required to pass complex data across the network or PHP pages. It is also used to store data(files, database, cookies etc). With this magic method call we can define the way how the data object will be stored. The __sleep() method should be used along with __wakeup() magic method. The __wakeup() magic method is called while unserializing the data and restores the serialized object to normal form.

< ?
class magicmethod
{
 function __sleep()
 {
  echo "Performing Clean-Up Operation Before Serializing Data ";
  return array("Serialized Data","1","2","3");
 }
}
$a = new magicmethod();
$serializedata = serialize($a);
echo $serializedata;
? >

Output:
Performing Clean-Up Operation Before Serializing Data
O:11:”magicmethod”:4:{s:15:”Serialized Data”;N;s:1:”1″;N;s:1:”2″;N;s:1:”3″;N;}

__wakeup()
This tutorial will guide you through the __wakeup() Magic Method. The __wakeup() magic method of PHP5 gets called when unserialize operation on object is performed. This method allows us to restore the serialized data to its normal form.

< ?
class magicmethod
{
 private $setName;
 function __sleep()
 {
  echo "Performing Clean-Up Operation Before Serializing Data ";
  $this->setName = "Hello World!!!";
  return array(setName);
 }
 
 function __wakeup()
 {
  echo "Performing Clean-Up Operation Before Unserializing Data ";
  echo $this->setName;
 }
}
$a = new magicmethod();
$serializedata = serialize($a);
$serializedata1 = unserialize($serializedata);
? >
 
 Output:
Performing Clean-Up Operation Before Serializing Data
Performing Clean-Up Operation Before Unserializing Data
Hello World!!!

__isset()
This tutorial will guide you through the __isset() Magic Method. The __isset() magic method in PHP5 is called whenever isset function of PHP is called to check for undeclared data member. With the help of this method we can check for the undeclared variables in the code. We can also set appropriate error message while testing for variable names getting used in the Class.

< ?
class magicmethod
{
 function __isset($variablename)
 {
  echo "Variable '".$variablename."' not Set";
 }
}
$a = new magicmethod();
isset($a->name);
? >

Output: Variable ‘name’ not Set

__unset()
This tutorial will guide you through the __unset() Magic Method. The __unset() magic method of PHP5 is called whenever unset function of PHP is called to clear an undeclared data member. With the help of this method we can check for the undeclared variables in the code. We can also set appropriate error message while testing for variable names getting used in the Class.


< ?
class magicmethod
{
 function __unset($variablename)
 {
  echo "Variable '".$variablename."' not Set and Cannot be UnSet";
 }
}
$a = new magicmethod();
unset($a->name);
? >



Output: Variable ‘name’ not Set and Cannot be UnSet



__autoload()
This methods get automatically called whenever you try to load an object of class which resides in separate file and you have not included those files using include,require and include_once. To use this method it is mandatory to the PHP filename as that of the class name because this methods accepts the class name as the argument. To know more about this method refer

Example – Basic AutoLoad Magic Method Usage

< ?
    function __autoload($classname)
    {
        include $classname.".php"; //Here $classname=magicmethod1
    }
 
    $a = new magicmethod1();
? >

Explanation for the Example:
Here i am trying to create an object of magicmethod1 class, but i have not included the magicmethod1.php so PHP compiler calls the __autoload() method which include that magicmethod1.php file.
Code for magicmethod1.php

< ?
    class magicmethod1
    {
        function __construct()
        {
            echo "MagicMethod1 Class Called";
        }
    }
? >

Output: MagicMethod1 Class Called
 



__clone()
In PHP 5 when you assign one object to another object creates a reference copy and does not create duplicate copy. This would create a big mess as all the object will share the same memory defined for the object. To counter this PHP 5 has introduced clone method which creates an duplicate copy of the object. __clone magic method automatically get called whenever you call clone methods in PHP 5.

< ?
class Animal
{
   public $name ;
   public $legs;
 
   function setName($name)
   {
 $this->name = $name;
   }
 
   function setLegs($legs)
   {
 $this->legs = $legs;
   }
 
   function __clone()
   {
 echo "
Object Cloning in Progress";
   }
}
 
$tiger = new Animal();
$tiger->name = "Tiger";
$tiger->legs = 4;
 
$kangaroo = clone $tiger;
$kangaroo->name = "Kangaroo";
$kangaroo->legs = 2;
 
echo "
".$tiger->name."---".$tiger->legs;
echo "
".$kangaroo->name."---".$kangaroo->legs;
? >
Output:
Object Cloning in Progress
Tiger—4
Kangaroo—2

No comments:

Post a Comment