group-icon
PHP Programming
Group for all things PHP, Coding Help, Problems and Solutions
104 Members
Join this group to post and comment.
Shruthi Pillai
Shruthi Pillai
Information Technology
31 Jan 2019

What are php magic methods

All functions starting with __ names are magical functions/methods. Magical methods always lives in a PHP class.The definition of magical function are defined by programmer itself.

Some of them are __construct(),__destruct(),__get(),__set(),__isset(),__unset(),sleep()

DHIRAJ LOTLIKAR
DHIRAJ LOTLIKAR
Information Technology
2mos ago

The function names __contruct(), __destruct(), __call(), __callStatic(), __get(), __set(),__isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debuginfo() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

Some of the above mentioned magic methods are explained below,

1) __sleep():

The intended use of __sleep() is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be    saved completely.

2) __wakeup():

The intended use of __wakeup()  to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

3) __tostring():

The __toString()  method allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR    level error is emitted.

4) __invoke():

The __invoke()  method is called when a script tries to call an object as a function.

5) __set_state():

This static method is called for classes exported by var_export() since PHP 5.1.0.

6) __debuginfo();

This method is called by var_dump() when dumping an    object to get the properties that should be shown. If the method isn't defined on an object, then all public, protected and private properties will be shown.