Sunday, June 11, 2017

Interview Questions and Answers - Object Orient Programming in PHP (OOP) - Intermediate

Question. No. 1:
What are magic methods ?

Answer:
  • __construct : called while initializing an object with a "new" keyword
  • __destruct : when object is going out of scope.
  • __call : When method doesn't exists or access restricted in Object scope
  • __callStatic : When method doesn't exists or access restricted in Static Scope
  • __get : when trying to read a variable which doesn't exist or access restricted
  • __set: when trying to set a variable which doesn't exist or access restricted
  • __isset : when trying to check isset a variable which doesn't exist or access restricted
  • __unset : when trying to unset a variable which doesn't exist or access restricted
  • __sleep :  when serialize an object in order to store in database 
class myClass
{

       var $var1 = 3; 

private $var2 = 2;
    public function __sleep()
    {
        return array('var1', 'var2');
    }
}
$myObj= new myClass;

serialize($myObj);
  • __wakeup : when un-serialize an object get serialize object then un-serialize it 
class myClass
{

       var $var1 = 3; 

private $var2 = 2;
    public function __wakeup ()
    {
        return array('var1', 'var2');
    }
}
$myObj= new myClass;

$se = serialize($myObj);

unserialize($se);
  • __toString: when a class object was printed as string this method will be called
class myClass
{
    public function __toString()
    {
        return 'class name';
    }
}

$myObj = new myClass;
echo $myObj;
  • __invoke : when declared ,it will be used as a callable function with instantiated object name. it takes same number of arguments passed.
class myClass
{
    public function __invoke($x,$y)
    {
        echo $x.$y;
    }
}
$myObj = new myClass;
$myObj (4,5);

  • __set_state : when var_export() function called on the object
  • __clone : when called clone on an object. when we try to tract the serials of cloned.
  • __autoload : its not a method but Function, 






No comments:

Post a Comment