What is PHP Magic Method, Why and How Should Use Magic Method

Magic method is called some predefined method of PHP which execute some event by the PHP compiler. The method start with the double underscore (__) known as PHP magic method (for example __construct, __destruct, __get, __set, __call etc). This is method is usually use inside any class. PHP has various magic method, I will try to discuss some most common magic method.

__construct:
The __construct method will called when someone create any instance/object of a class. This method usually declared at first of a class, but there is no any strict rules where we need to declare it. We can declare is anywhere in our class. and also we can inherit this method.

__destruct:
The __destruct method is called when object is destroyed, it’s opposite of __construct method. This method usually declared at last of a class, but there is no any strict rules where we need to declare it. We can declare is anywhere in our class.

__get:
The get method is called when anyone want to read/get the value of property or variable.

__set:
The __set method is called when someone want to set value of a property or variable.

__isset:
The __isset method is called when someone applied isset() method anywhere in a class.

__unset:
__the __unset method is called when someone applied unset() method anywhere in a class, which i really opposite of isset method.

__call:
The __call method is called when someone try to call a normal method.

__sleep:
The __sleep method is called when someone trying to serialize his class object.

__wakeup:
The __sleep method is called when someone trying to deserialize his class object.

__toString:
The __toString method is called when someone try to print the object of a class.

Example: