Understanding of php magic methods

藏色散人
Release: 2023-03-05 21:36:02
Original
3437 people have browsed it

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.

Understanding of php magic methods

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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template