PHP | Magic Methods with examples

What is Magic Methods in PHP: PHP Magic Methods are some special functions that will be called automatically. Such functions require no function call to execute the code inside these functions. With this special feature, they can be referred as magic functions or magic methods.

PHP Magic Methods

Following are the list of PHP magic methods with descriptions:

Method NameDescription
__construct()the constructor of a class
__destruct()the destructor of a class
__call($funName, $arguments)The __call() method will be called when an undefined or inaccessible method is called.
__callStatic($funName, $arguments)The __callStatic() method will be called when an undefined or inaccessible static method is called.
__get($propertyName)The __get() method will be called when getting a member variable of a class.
__set($property, $value)The __set() method will be called when setting a member variable of a class.
__isset($content) The __isset() method will be called when calling isset()  or empty() for an undefined or inaccessible member.
__unset($content)The __unset() method will be called when calling reset() for an undefined or inaccessible member.
__sleep()The __sleep() method will be called first when executing serialize().
__wakeup()The __wakeup() method will be called first when deserialization() is executed.
__toString()The __toString() method will be called when using echo method to print an object directly.
__invoke()The __invoke() method will be called when trying to call an object in a way of calling function.
__set_state($an_array)The __set_state() method will be called when calling var_export().
__clone()The __clone() method will be called when the object is copied.
__autoload($className)Try to load an undefined class.
__debugInfo()Print debug information.

You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

Caution: PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.

Example #1 Sleep and wakeup

It is not possible for __sleep() to return names of private properties in parent classes. Doing this will result in an E_NOTICE level error. Instead you may use the Serializable interface.

Reference: https://www.php.net/manual/en/language.oop5.magic.php

If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.

Recommended Posts:


Editorial Staff

Editorial Staff at FreeWebMentor is a team of professional developers.