Home > DeveloperSection > Articles > Magic method in PHP

Magic method in PHP


PHP PHP 
Ratings:
0 Comment(s)
 472  View(s)
Rate this:

Magic method in PHP


The magic methods are one with special names which are executed in response to some events. These magic methods are predefined function by PHP compiler, starting with two underscore “__”, which indicate methods, which will be triggered by some PHP events. These functions are always defined inside the class and are not defined outside the class (they are not standalone functions).The magic function available in PHP are: __call(), __construct(), __destruct(),  autoload(),  __callstatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(),  __tostring(), invoke() and __clone(). In this section you will learn about the magic method with the help of an example:

__construct()

The __construct() is the most common method in PHP. This is because in PHP 5 version, __construct() is basically the constructor of your class. This method is automatically called once an object is created. This means you can inject parameters and dependencies to set up an object.

Notes If PHP 5 could not find the __construct() method then it will search for a function with the same name as that of class name(this is an older method to write constructor ). Please note __construct() method is not included in PHP 4.

Now, here is an example of __construct() method

<?php

class Myname

{

public function __construct($name)  

{

  $this->name = $name;

 

}

 }

$Myname = new Myname('Neha Singh');

echo $Myname->name;      // display Neha Singh

 

?>

 

Now, when you create the instance of Myname object, you will pass the parameters which will be inserted into __construct() method. As you can see from the above example you don’t need to call the method it is automatically called.

__ destruct ()

In PHP __destruct() method is opposite of __construct() method. The __destruct() method is automatically called when an object of a class is destroyed. This method is needed as it provides necessary cleanup operations like closing database connection, unsetting internal class objects. In PHP 4 the concept of destructor is not mentioned .In simple words, __ destruct() is used to delete an object.

Notes   A destructor cannot take any arguments.

Now, here is an example of __ destruct () method

<?php

class test

{

          public  function __destruct()

          {

                   echo  'object is destroyed’;

          }

}

 

$obj = new test();

 

 

echo 'hello world';

?>

 

__autoload()

In PHP __autoload() function makes the job easier for the programmer by including classes automatically without writing the large number of include or require statement. You don’t need to call this function .Instead it will be called automatically or behind the scene by PHP-that’s why it is magical.

Now, here is an example to explain how it actually works.

include "class/class.First.php";

include "class/class.Third.php";

include "class/class.Fourth.php";

 

$ First = new First;

$ Third = new Third;

$ Fourth = new Fourth;

 

In the above code we have to include 4 different class separately as we are creating an instance of each class. But imagine if we have to use 40 classes within this one file-writing include statement for each class will become a huge pain for developers. So, __autoload() method solve this problem, it will load the class automatically. Let’s understand with the help of an example how it will do.

function __autoload($class_name)

{

   include_once “./class/class.”.$class_name.“.php”;

}

 

$ First = new First;

$ Second = new Second;

$ Third = new Third;

$ Fourth = new Fourth;

 

__call()

If there is a __call() function in a class and that class is called with a  method that don’t even exist -__call() is triggered instead. This method is called automatically when the program execute a method that don’t even exist.

__call() takes two arguments. First is the name of the undeclared method and second is the array that contains a list of parameters.

Now, here is an example of __call() method

class  Myname

 {

   function __call($fname, $parameter) {

     

  }

}

 

$obj = new Myname;

$obj->text()        // as text() method does not exist it will trigger __call

__callstatic()

The _callstatic() method is similar to _call() method the only difference between them is that  it is called when code attempts to call static method.

__callstatic is a static magic method which will be executed when any method of a class is called by static techniques.

Now, here is an example of __callstatic() method

<?php

class Gadget{

  

    public static function  __callStatic($fname, $arguments) {

        echo "This is a magic method!!";

    }

  

}

 

 

Gadget::iDontExist();

 

__get() & __set()

__get() method is executed when inaccessible property of ea method is called . In other words, __get() is called when code attempts to access a property that is not accessible. A major use of __get() method is to extend the access control by creating “read-only” properties. This method takes one arguments.

__set() method is run when writing data to inaccessible properties.

Now, here is an example of __get()method. __get() takes two arguments.

<?php

class test {

 

    public $text;

    public function __get($fname) {

 

        echo "Get:$fname";

        return $this->$fname;

    }

 

    public function __set($fname, $value) {

 

        echo "Set:$fname to $value";

        $this->$fname = $value;

    }

}

 

 

$ test = new test ();

 

echo $test -> text;

$test -> text = 'Neha singh';

 

echo "[$test -> text]";

?>       // It will only print Neha singh'

 

__isset() and __unset()

 

__isset() and __unset() methods are opposite to each others.

__isset() magic method executes when isset() function is applied on property which is not accessible or not defined. It takes name of the parameter as an argument.

__unset() is opposite of unset() method which is triggered when unset() method is applied which is not accessible or not defined.. It takes name of the parameter as an argument.

__isset() and __unset() both takes one arguments. Following is an example of __isset and __unset methods:

<?php

class text

{

function __isset($fname)

{

echo "__isset is called for $fname";

}

function __unset($fname)

{

echo "__unset is called for $fname";

}

}

$obj = new text ();

isset($obj->a);

unset($obj->b);

?>

 

__sleep()  & __wakeup()

The __sleep() and __wakeup() method are called when an object is serialized. __sleep() method is called when object is about is to be serialized whereas as __ wakeup() method is just opposite of __sleep() where an object of a class is about to be unserialized.  Both __sleep and __wakeup does not accept any parameter nor return any value.

<?php

class sleepWakeup {

 

    public function __construct() {

      

    }

 

    public function __sleep() {

        echo 'This is sleep magic method.'."</br>";

    }

 

    public function __wakeup() {

        echo 'This is wakeup magic method.';

    }

 

}

 

$obj = new sleepWakeup();

 

// calling __sleep method

echo $obj->__sleep();

 

 

 

// calling __wakeup method

echo $obj->__wakeup();

?>

 

__invoke()

__invoke() method is called when you use object of a class as a function. __invoke() magical method does not take any parameter.

Now, here is an example of __invoke():

<?php

function text(Callable $function) {

  $function();

  return "This is an invoke method";

}

 

class term {

  public function __invoke() {

    echo "Hello world!!"."</br>";

  }

}

 

$obj = new term();

echo text($obj);

?>

.

__tostring()

__tostring() is also one of the magical method which is used for debugging purposes. The __tostring() method is automatically called when an object in PHP 5 is converted into string for concatenation or display purpose.

__tostring executes when you are using echo on your object.

<?php

// Declare a simple class

class Test

{

    public $text;

 

    public function __construct($text)

    {

        $this->text = $text;

    }

 

    public function __toString()

    {

        return $this->text;

    }

}

 

$obj = new Test('Hello World!!!');

echo $obj;

 

__clone()

__clone is a magical method which is used to create duplicate of an object.In case of regular variables, $x=$y means that a variable $x gets created and contains the value of $b which means two variables get created.

With object $ob1 = $ob2 does not mean $ob1 is created, it means the reference of ob2 is assigned to $ob1.

public function __clone()

{

    $this->someObject = clone $this->someObject;

}


Don't want to miss updates? Please click the below button!

Follow MindStick