what are magic methods in PHP?

This post will give you very simple and basic understanding of magic methods in PHP. That is, “The function name which start with double underscore “__” are called magic functions.”  Those are Always  defined inside classes, they could not be stand alone functions.

The reasons behind the name “magic functions” is,

  • The programmer has to define the definition of magic functions. PHP does not provide the definitions of the magic functions.
  • Magic functions will never directly called by the programmer. Actually, PHP will call the magic function ‘automatically based on requirement’.

So many magic functions available in PHP : __construct(), __destruct(), __call(), __autoload(), __get(), __set(), __isset(), __unset(), __wakeup(), __toString(), __invoke(), etc. some more magic functions are also available. Magic functions are like a widgets for programer, which can be utilize for powerful programing.

Lets just take one simple example of “__construct()” to make it more simple. This most commonly used magic function, This function is introduce with PHP5. Programmer will give the definition of the __construct function, but that will called automatically while the object of class is define.

Here is an example,

class Area
   public $height;      // height
   public $weight;     // weight

   public function __construct($height, $weight) 
     $this->height = $height;  //set the height
     $this->weight = $weight;  //set the weight

In above code, we have a simply define __construct function, which will set height and weight of area object. In bellow line we have just create object of area calls.

$area = new Area(10, 50);

So finally what happen here, we have just define the construct function, which is to set height and width of and object. Now when we will create an object it will automatically called __construct function and set the values of variables. This is the magic of magic functions.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s