Thursday, April 4, 2013

OOP -> Magic Methods

Magic Methods are methods of a class that call automatically on some situation, if they are defined within that class.


For example, if you have defined __construct in a class, whenever you create an object of that class. __construct will call automatically.

Properties of magic methods
Call automatically, if defined within that class
Start with double underscore (__)
Called implicitly
Introduce in PHP5

Following are the magic methods and their property
  • __construct() called when create instance of a class. 
  • __destruct() called when destroy the object. 
  • __call()  called when try to access a function that does not exist within class.
  • __callStatic() called when try to access a function that does not exist within class in static context.
  • __get() called when trying to get data that is not exist.
  • __set() called when trying to writing data to inaccessible properties. 
  • __isset() called when use isset / empty function on inaccessible variable.
  • __unset() called when us unset with inaccessible variable.
  • __sleep() called prior to any serialization 
  • __wakeup() called prior to any un-serialization.
  • __toString() called when echo the class object.
  • __invoke() called when a script tries to call an object as a function.  
  • __set_state() called when classes exported by var_export() since PHP 5.1.0.
  • __clone() called after using clone function.
Following are the Example of __toString magic method.
class TestClass{
    public $foo;
    public function __construct($foo) {
        $this->foo = $foo;
    }
    public function __toString()
    {
        return '__toString function called';
    }
}

$class = new TestClass('Testing');
//testing __toString magic method
echo $class;


2 comments: