[php classes and objects] magic methods

不言
Release: 2023-03-23 20:54:01
Original
1658 people have browsed it

The content shared with you in this article is about [php classes and objects] magic methods, which has a certain reference value. Friends in need can refer to it

Magic methods(Magic methods)

__construct()__destruct()__callStatic()__set()__isset()__unset()__wakeup()__invoke()__clone() __debugInfo()
Copy after login

__sleep() and __wakeup()

public array __sleep ( void )void __wakeup ( void )
Copy after login

__sleep() is used to submit uncommitted data, or similar cleanup operations. For example, there are some very large objects, but they don't all need to be saved.

__wakeup() is used for deserialization operations. For example, re-establish the database connection or perform other initialization operations.

serialize() will check 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.

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.


Explanation of the above concepts

Serialize can convert variables, including objects, into continuous bytes data. You can save the serialized variables in a file or in Transmit over the network. Then deserialize it back to the original data. For a class you define before deserializing the object of the class, PHP can successfully store its object's properties and methods. Sometimes you may need an object to be deserialized before deserializing it. Executed immediately after serialization. For this purpose, PHP will automatically look for the __sleep and __wakeup methods.

When an object is serialized, PHP will call the __sleep method (if it exists). In After deserializing an object, PHP calls the __wakeup method. Neither method accepts parameters. The __sleep method must return an array containing the properties that need to be serialized. PHP discards the values ​​of other properties. If there is no_ _sleep method, PHP will save all attributes.

Before the program is executed, the serialize() function will first check whether there is a magic method __sleep. If it exists, the __sleep() method will be called first and then executed. Serialization (serialization) operations. This function can be used to clean an object and return an array containing the names of all variables in the object. If the method returns nothing, NULL is serialized, resulting in an E_NOTICE error. In contrast, unserialize() checks whether there is a __wakeup method. If it exists, the __wakeup method will be called first to prepare the object data in advance.

__sleep method is often used to submit uncommitted data, or similar operations. At the same time, this function is very useful if you have some large objects that do not need to be saved. __wakeup is often used in deserialization operations, such as re-establishing a database connection, or performing other initialization operations.


__toString()

is used for how a class should respond when it is treated as a string. For example, echo $obj; should display something.
This method must return a string, otherwise a fatal error of E_RECOVERABLE_ERROR level will be issued. Exceptions cannot be thrown in the __toString() method. Doing so will result in a fatal error.

Example #2 简单示例<?php// Declare a simple classclass TestClass{
    public function __toString() {
        return &#39;类被当成字符串时tostring返回字符串&#39;;        // return intval(&#39;tostring返回值的内容不为字符串&#39;);//Recoverable fatal error: Method TestClass::__toString() must return a string value
    }
}$class = new TestClass();echo $class;//echo (string)$class; // 未定义 __toString()方法,并将对象转换为字符串,报错Recoverable fatal error: Object of class TestClass could not be converted to string?>
Copy after login

It should be pointed out that
Before PHP 5.2.0, the __toString() method can only take effect when used directly with echo or print.
After PHP 5.2.0, it can be used in any string environment (such as through printf(), using the %s modifier), but cannot be used in non-string environments (such as using the %d modifier).
Since PHP 5.2.0, if an object that does not define the __toString() method is converted to a string, an E_RECOVERABLE_ERROR level error will be generated.


__invoke()

mixed __invoke ([ $... ] )
Copy after login

When trying to call an object by calling a function, the __invoke() method is automatically called. (PHP 5.3.0)

Example #3 使用 __invoke()<?phpclass CallableClass {
    function __invoke($x) {
        var_dump($x);    //int(5)
    }
}$obj = new CallableClass;$obj(5);
var_dump(is_callable($obj));   //bool(true)?>
Copy after login

__set_state()

Related recommendations:

[php class and Object】Traversal

【php classes and objects】Anonymous class

【php classes and objects】Overload

The above is the detailed content of [php classes and objects] magic methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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