PHP Magic Methods

MAGIC METHODS

1.Why magic methods ?

Ans:

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 if 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.

  1. Magic methods are member function that is available for all instance of class.
  2. Magic method stars with __(double underscore), like: __get () ,__set()
  3. Magic methods are always declared as PUBLIC.

LIST of MAGIC METHODS used in PHP 5 :

__get() , __set() , __autoload , __sleep() , __wakeup() , __construct() , __destruct() , __isset() , __unset() , __clone , __call ,__toString()

1. __construct() :- This methods gets called whenever an object of a class is instantiated.

2. __destruct() :–  This methods gets called whenever an object of a class is destroyed or object goes out of scope.

3. __set() :–  This methods get automatically called whenever you assigns data to a undefined attributes of an class in PHP 5. With this method the programmer can keep track on the variables which are not defined inside the class.

    Syntax:

    < ?

    function __set($data,$value){

    //$data – holds the name of the undefined attributes

    //$value – holds the value assigned to the undefined attributes.

    }

    ?>

    Example:

    < ?
    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;
    ?>
    In Above example : 

      Output:
      Error assigning values to undefined attributes
      attributes Called:setData
      Value assigned to attributes:20

      Explain:

      In the magicmethod class setData is not defined so the php compiler excutes __set() magic method and displays error message.

      And  assigned value 20 to an attribute setData of magicmethod class.

      5. __get() :- This methods get automatically called when you try to retrieves the data of undefined attributes of an class in PHP 5.

        Syntax:

        function __get($data)
        {
             //$data holds the name of the undefined attributes getting called.
        }
          
        Example:
        < ?
        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
         
        Explain: 
        a.echo an attribute setData of magicmethod class.
        b.But in the magicmethod class setData is not defined so the php compiler excutes __get() magic method and displays error message 
        
        6.__cal() :- 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.

          Syntax:

          < ?
          function __call($data,$argument)
          {
                         //$data holds the name of the undefined method getting called.
                  //$argument holds the argument passed to the method.
          }
          ?>

          Example:

          < ?
          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)

          Explain:

          1.trying to call setData method of magicmethod class.

          2.Now in the magicmethod class setData is not defined so the php compiler excutes __call() magic method and displays error message.


          6. __sleep() :-  This methods gets called when you serialize the object in PHP 5. Serializing is required to pass complex data across the network or PHP pages. It is also used to store data(files, database, cookies etc).

            Syntax:

            < ?
            function __sleep()
            {
                           ...
                           return serialised data;
            }
            ?>

            Example:

            < ?
            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;}

            Explain:

            a.trying to serialize the object of magicmethod class.

            b.Now the PHP Compiler calls the __sleep() Magic method which return an array having the serialized values

            7.__wakeup() :- This methods gets called when the object is about to be unserialized in PHP 5. This method allows us to restore the serialized data to its normal form.

            Syntax:

            function __wakeup()
            {
                           ...
            } 
            

            Example:

            < ?
            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!!!

            Explain:

            a.trying to serialize the object of magicmethod class

            b.Now the PHP Compiler calls the __sleep method which return an array having the serialized values

            c. After serialize data, i am calling the unserialize function; now the PHP compiler will call the __wakeup method which contains the original data that was serialized .

            8. __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.

              Syntax:

              < ?
                 function __autoload($classname)
                 {
                    require($classname.".php");
                 }
              //$classname is the name of the Class.
              ?>

              Example:

              //magicmethod1.php

              < ?
                  class magicmethod1
                  {
                      function __construct()
                      {
                          echo "MagicMethod1 Class Called";
                      }
                  }
                ?>
              <?php
                  function __autoload($classname)
                  {
                      include $classname.".php"; //Here $classname=magicmethod1
                  }
               
                  $a = new magicmethod1();
              ?>

              Output: MagicMethod1 Class Called

              Explain:

              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.

              9.__clone() :- PHP5 has introduced clone method which creates an duplicate copy of the object. __clone methods automatically get called whenever you try to call clone methods in PHP 5. This operator does not creates a reference copy.

                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

                Example:

                //without cloning

                < ?
                class Animal
                {
                   public $name;
                   public $legs;
                 
                   function setName($name)
                   {
                               $this->name = $name;
                   }
                 
                   function setLegs($legs)
                   {
                               $this->legs = $legs;
                   }
                }
                 
                $tiger = new Animal();
                $tiger->name = "Tiger";
                $tiger->legs = 4;
                 
                $kangaroo = $tiger;
                $kangaroo->name = "Kangaroo";
                $kangaroo->legs = 2;
                 
                echo $tiger->name."---".$tiger->legs;
                echo "<br />".$kangaroo->name."---".$kangaroo->legs;
                ?>

                Output:
                Kangaroo—2
                Kangaroo—2

                Explanation:

                • Here i have created an $tiger object of Animal class
                • Created another variable $kangaroo and assigned $tiger to $kangaroo
                • After echo it print the details entered last because both the variables are referring to the same memory location

                Example:

                //with __Clone

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

                Output:
                Object Cloning in Progress
                Tiger—4
                Kangaroo—2

                Explanation:

                • Here i have created an $tiger object of Animal class
                • Created another variable $kangaroo having clone of $tiger. This calls the __clone magic method
                • After echo it print the details entered by individual object as both of them are referring to separate object and memory location

                The above technique of cloning discussed is called shallow copy. There are other techniques called Deep Copy wherein you create duplicate copy of objects referring to other objects etc.

                10. __toString() :- __toString method is called when PHP needs to convert class instances into strings, for example when echoing:

                <?php

                class SomeClass {
                public function __toString() {
                return ‘someclass’;
                }
                }

                $obj = new SomeClass();
                echo $obj;
                //will output ‘someclass’

                ?>

                11. __isset() :- This methods get automatically called whenever you try to check the existence of the undeclared attributes of the class using isset function of PHP.

                12. __unset() :- This methods get automatically called whenever you try to check the destroy or clear an undeclared attributes of the class using unset function of PHP

                Advertisements

                One Response

                1. Wow! Awesome and thorough post – very helpful, this is nice too for understanding magic methods:

                  http://www.programmerinterview.com/index.php/php-questions/php-what-are-magic-functions/

                Leave a Reply

                Fill in your details below or click an icon to log in:

                WordPress.com Logo

                You are commenting using your WordPress.com account. Log Out / Change )

                Twitter picture

                You are commenting using your Twitter account. Log Out / Change )

                Facebook photo

                You are commenting using your Facebook account. Log Out / Change )

                Google+ photo

                You are commenting using your Google+ account. Log Out / Change )

                Connecting to %s

                %d bloggers like this: