Programming Language

In PHP, What Are Magic Methods And How Are They Used?

PHP, a general programming language as well as a web development language has the feature of “magic methods”. In PHP, magic methods are used in Object oriented programming (OOP). The magical terms are distinguished by placing prefix of two underscores “__”.

Magic functions in PHP:

  • __construct(), __destruct()
  • __call(), __callStatic()
  • __isset(), __unset()
  • __set(), __get()
  • __wakeup(), __sleep()
  • __set_state(), __invoke() __toString()
  • __clone(), and __autoload()

What is the reason behind calling them magic functions?

There is an interesting reason behind why magic functions are identified as “magical”. You as a programmer input the definition in front of the method, till then they are not defined. Programmer is the one to define it by writing the code which gives it the command to carry out a certain task in PHP. There is no command provided by PHP in its terms.

Now that you write a code, you can never instruct the function to run directly. PHP itself runs the function for you behind the screen. This is the reason they are called “Magic Methods/Functions”. You write a code, define it, but PHP gives it a call on time instead of your direct instruction.

How are they used?

A PHP magic method/function is written with a double underscore “__” before its function name. Their definition is given inside classes. A double underscore “__” represents a magical obscure function of the code.

 

Example:

This an example of two PHP magic methods:

__constructor() and destructor()__

A class consisting of constructor method contains the definition of initialization which certain objects may require.  Whereas a class consisting of destructor methods has the definition to destruct the object when it’s of no use.

class MyDestructableClass {

function __construct() {

print “In constructor\n”;

$this->name = “MyDestructableClass”;

}

 

function __destruct() {

print “Destroying ” . $this->name . “\n”;

}

}

 

$obj = new MyDestructableClass();

 

 

When the useful magic methods are encoded, they act as hinderer before runtime until certain criteria is met. It makes them useful and magical.

Leave a Reply