Home > Article > Backend Development > Understanding of php magic methods
In PHP, all class methods starting with "__", that is, two underscores, are reserved as magic methods. The magic methods in PHP include "__construct()", "__destruct()", and "__call()" , "__callStatic()", "__get()" and so on.
Recommended: "PHP Video Tutorial"
Magic Method
__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state (), __clone() and __debugInfo() are called magic methods in PHP. You cannot use these method names when naming your own class methods unless you want to use their magic functionality.
Caution
PHP reserves all class methods starting with __ (two underscores) as magic methods. Therefore, when defining class methods, except for the above magic methods, it is recommended not to prefix them with __.
__sleep() and __wakeup()
public __sleep ( void ) : array
#__wakeup ( void ) : void
serialize( ) function checks whether there is a magic method __sleep() in the class. If present, this method will be called first, and then the serialization operation will be performed. This function can be used to clean an object and return an array containing the names of all variables in the object that should be serialized. If the method returns nothing, NULL is serialized and an E_NOTICE level error is raised.
Note:
__sleep() cannot return the name of the private member of the parent class. Doing so will generate an E_NOTICE level error. The Serializable interface can be used instead.
__sleep() method is often used to submit uncommitted data, or similar cleanup operations. At the same time, this function is useful if you have some large objects but do not need to save them all.
In contrast, unserialize() checks whether there is a __wakeup() method. If it exists, the __wakeup method will be called first to prepare the resources needed by the object in advance.
__wakeup() is often used in deserialization operations, such as re-establishing a database connection, or performing other initialization operations.
The above is the detailed content of Understanding of php magic methods. For more information, please follow other related articles on the PHP Chinese website!