15 magic methods in PHP

Introduction –

Magic methods is special type of function that start with  __( double underscore ) and its execute automatically after PHP events is triggered. we use this magic method to override PHP default action.

Lets move to explain magics methods one by one which is available in PHP.

 

magic methods in PHP
magic methods in PHP

__construct

This magic methods is called automatically just after creating the object of class.It is used to pass the parameters and assigns value for data member of given class. It can be  inherited the parent class properties values by using parent::construct. Before calling class, when we need to load library or database connection , we just defined in __construct methods because this magics methods is called automatically when we initialize the object.

function __constrct(parametr1 ,parameter2...){

    //code start here
    //initilize the value for member variable

}

we want to implement this construct methods in class , Please have a look at below code about construct methods implementation in class object.

 

class AutoMobile
    {                                                                     
            public $name;       
            public $model;       
            public $price;       

        /**
         * explicitly declare a constructor with parameters
         */                                                                                       
        public function __construct($name="", $model="vxi", $price=900)
        {     
            $this->name = $name;
            $this->model = $model;
            $this->price = $price;
        }

        /**
         * say method
         */
        public function say()
        {
            echo "Name:" . $this->name . ",model:" . $this->model . ",Price:" . $this->price;
        }   

    }

We Create object $car without any parameters.

$car = new AutoMobile();
echo $car->say(); //print:Name:,model:vxi,price:900

 

when we Create another object $car2 with parameter “SWIFT“.

$car2 = new AutoMobile(“SWIFT”);
echo $car2->say(); // /print:Name:SWIFT,model:vxi,price:900

When we create another object $car3 with three parameters.

$car3 = new 

AutoMobile

("SWIFT", "vxi", 900);
echo $car3->say(); // // /print:Name:SWIFT,model:vxi,price:900

__destruct()

It is just opposite of __construct() magic methods in PHP. It is run automatically run after just destroy objects.It allows to
performs some operation before destroying objects such as closing file or empty result etc..

Example - 

class MyClass{
  function __destruct(){
    // Code within this magic method
  }
}
$object = new MyClass();

 

class MyClass{
  function __construct(){
    echo " Its executed cautomatically when the class object created ";
  }
      public function __destruct(){
        echo " It is called automatically when the script has to shut down. " ;
        // save object state as well as clean up other memory space
}
}

$object = new MyClass();

Output 

Its executed cautomatically when the class object created It is called automatically when the script has to shut down.

 

We have used two magics function __construct and __destruct both are executed just after object gets created. whatever in __construct will be freed up and clean up using __destruct automatically just after created the objects  of new class.

 

__call() –

This magic methods is used when we access nonexistence methods or inaccessible methods in class. This methods helps to solve issue for method overloading in PHP.

Lets have example for better understand –

 

Syntax:

public __call ( string $methodname , array $arguments ){

  
}

 

Now we implement __call methods in complete class .

 

<?php
class Car{
    public function __call($name, $argu){
       
        if( $name =='name'  ){

               echo 'This is my swift';
        }
}
}
$obj = new Car();
$obj -> name('This is my car');
?>

Output -    This is my swift

 

__callStatic()

It is used for creating   inaccessible  static methods . When we want to call static methods that not exist in class then this magic methods called automatically .

Syntax  –

public __callStatic (string $methodname , array $arguments){



}

 

Lets take a look at implementation of this magic methods in class.

<?php
class Car{
    public static function __callStatic($methodname, $argu){
      
           if(  $methodname =='name' ){
                     echo 'This is example of nonexistance static method';
               }
}
}
$obj = new Car();
Car::name ('This is non existance methods in class');
?>

Output -  This is example of nonexistance static method

 

__set()

 

This is very popular magic methods in PHP, when we used to write data on inaccessible or non existence properties of class. This methods called automatically when we call undefined variable in class.

 

Syntax –

 

public __set(string $variablename , mixed $value){
  
}

Lets implement __set magics methods in our calss.

 

<?php
class Car{
    private $name = array();
    public function __set($model, $value){
    
        $this->name[$model] = $value;
}
}
$obj = new Car();
 

$obj->model = 'VXI';
?>

Here we have pass two parameters 1st parameters is property name and 2nd parameters $value , which is set for property $model. When we want to access model property that is defined anywhere in class then automatically called the __Set magics methods.

__get():

It is also very popular magics methods that is used to read inaccessible or non existence  property in our class.

Syntax:

public __get ( string $name ){



}

 

Lets look at that below code for implementing in our class.

<?php
class User{
    private $details = array();
    public function __set($n, $val){
        $this->details[$n] = $val;
    }
 
    public function __get($n){
        if (isset($this->details[$n])){
            return $this->details[$n];
        }
}
}
$obj = new Car();
//  automatically called __set() 
$obj->phone = '8810458878';   
//  automatically called __get()
echo $obj->phone;                      
?>

As we see in above code, We want to read private property of this class, Where we used __set methods to set assign value for non existence property after that we get this property by using __get magics methods.

 

__sleep()

When we use serialize() methods , It checks __sleep magics methods in class , if it exists then called automatically in our class first then serialization will perform .

__sleep() method is used to serialize selected properties   before saving data into database.

 

class User
{
    public $sex;
    public $name;
    public $age;

    public function __construct($name="",  $age=25, $sex='Male')
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }

 
    public function __sleep() {
        echo "This method is called when the serialize() method is called from outside class.<br>";
        $this->name = base64_encode($this->name);
        return array('name', 'age'); 
    }
}

$user = new User('Devis'); // Initially assigned.
echo serialize($person);
echo '<br/>';

 

Output  –

This method is called when the serialize() method is called from outside class.
O:6:"User":2:{s:4:"name";s:8:"5bCP5piO";s:3:"age";i:25;}

__wakeup()

It is called automatically when we used unserialize() methods  from outside class. It helps to re established database connection and start up any task.

class User
{
    public $sex;
    public $name;
    public $age;

    public function __construct($name="",  $age=25, $sex='Male')
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }

 
    public function __wakeup() {
        echo "This  is called automatically when the unserialize() method is called from outside the class.<br>";
        $this->name = 2;
        $this->sex = 'Male';
        // There is no need to return an array here.
    }
}

$user = new User('Devis'); // Initially assigned.
var_dump(unserialize(serialize($user)));
echo '<br/>';

Output –

This is called automatically when the unserialize() method is called from outside the class.
object(Person)#2 (3) { ["sex"]=> string(3) "Male" ["name"]=> int(2) ["age"]=> int(25) }

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *