Tuesday 6 September 2011

PHP Magic Methods with Examples

PHP Magic Methods with Examples

Explain the Magic Method in Detail


The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(),  __debugInfo() and __clone() are magical in PHP classes.

1) You cannot create any usr-defined function with double underscore (i.e __) because double underscore is reserved.
2) Magic Methods are start with double underscore (i.e __).
3) When we create any magic method in class start calling automatically. that's why called magic method.



__construct
When we make init an class object, It will call __construct method.


__destruct
When class scope end, It will call __destruct method.


__call
When we make trying to access inaccessible methods, It will call the __call method.


__callStatic
When we make trying to access inaccessible methods in static, It will call the __callStatic method.


__get
When we make trying to access inaccessible variable, It will call the __get method.


__isset()
When we make trying to calling isset() or empty() on inaccessible properties, It will call the __isset method.


__unset()
When we make trying to calling unset on inaccessible properties, It will call the __unset method.


__sleep()
When we are using serialize() function, It will check for __sleep(). If __sleep() is defined, this function is executed prior to any serialization.


__wakeup()
When we are using unserialize() function, It will check for __wakeup(). If __wakeup() is defined, this function is executed prior to any unserialization.


__toString()
When we try to print an object, It will call __toString() function (if defined).


__invoke()
When we try to call object as function, It will call __invoke() function (if defined).


__set_state()
When we are using var_export() function, It will check for __set_state(). If __set_state() is defined, this function is executed prior to any var_export().


__debugInfo()
When we are using var_dump() function, It will check for __debugInfo. If __debugInfo is defined, this function is executed prior to any var_dump().



Example of __sleep and __wakeup:

/** class to test magic method i.e sleep and wakeup **/
  class magicmethod
{
    public $name1 = 'Hello';
    function __wakeup()    {  
        echo "__wakeup funx called \n";
        echo $this->name1;
    }
    function __sleep(){  
        echo "__sleep funx called \n";
        $this->name1 ='Arun kumar';
        return array('name1');
    }
}
$obj = new magicmethod();
$objString = serialize($obj);
echo $objString;
echo '\n' ;
unserialize($objString);


Output

__sleep funx called

O:11:"magicmethod":1:{s:5:"name1";s:10:"Arun kumar";}  
__wakeup funx called 
Arun kumar