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() 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.  See Example Below:

/** 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' ;


__sleep funx called

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

Other Exmples : click

Second Video

No comments :

Post a Comment