In PHP, what are magic methods and how are they used?

PHP functions that start with a double underscore – a “__” – are called magic functions (and/or methods) in PHP. They are functions that are always defined inside classes, and are not stand-alone (outside of classes) functions. The magic functions available in PHP are: __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone(), and __autoload().

Why are they called magic functions?

The definition of a magic function is provided by the programmer – meaning you, as the programmer, will actually write the definition. This is important to remember – PHP does not provide the definitions of the magic functions – the programmer must actually write the code that defines what the magic function will do. But, magic functions will never directly be called by the programmer – actually, PHP will call the function ‘behind the scenes’. This is why they are called ‘magic’ functions – because they are never directly called, and they allow the programmer to do some pretty powerful things. Confused? An example will help make this clear.

Example of using the __construct() magic function in PHP

The most commonly used magic function is __construct(). This is because as of PHP version 5, the __construct method is basically the constructor for your class. If PHP 5 can not find the __construct() function for a given class, then it will search for a function with the same name as the class name – this is the old way of writing constructors in PHP, where you would just define a function with the same name as the class.

Now, here is an example of a class with the __construct() magic function:

class Animal {

public $height;      // height of animal  
public $weight;     // weight of animal

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



In the code above, we have a simple __construct function defined that just sets the height and weight of an animal object. So let’s say that we create an object of the Animal class with this code:

Animal obj = new Animal(5, 150);

What happens when we run the code above? Well, a call to the __construct() function is made because that is the constructor in PHP 5. And the obj object will be an object of the Animal class with a height of 5 and a weight of 150. So, the __construct function is called behind the scenes. Magical, isn’t it?

If you’re looking for another example of a magical function, then just check out the next page – where we give an example of the __autoload function in PHP and how it’s used.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

Leave a Reply

Your email address will not be published.