Home > Article > Backend Development > Detailed explanation of __sleep() method in PHP
__sleep(), when executing serialize(), this function will be called first
serialize() function will check whether there is a magic method __sleep() in the class. If it exists, this method will be called first, and then the serialization operation will be performed.
This function can be used to clean the 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 generated.
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.
Function:
__sleep() method is often used to submit uncommitted data, or similar cleaning operations. At the same time, this function is useful if you have some large objects but do not need to save them all.
Please refer to the following code for details:
<?php class Person { public $sex; public $name; public $age; public function __construct($name="", $age=25, $sex='男') { $this->name = $name; $this->age = $age; $this->sex = $sex; } /** * @return array */ public function __sleep() { echo "当在类外部使用serialize()时会调用这里的__sleep()方法<br>"; $this->name = base64_encode($this->name); return array('name', 'age'); // 这里必须返回一个数值,里边的元素表示返回的属性名称 } } $person = new Person('小明'); // 初始赋值 echo serialize($person); echo '<br/>';
Code running results:
当在类外部使用serialize()时会调用这里的__sleep()方法 O:6:"Person":2:{s:4:"name";s:8:"5bCP5piO";s:3:"age";i:25;}
The above is the detailed content of Detailed explanation of __sleep() method in PHP. For more information, please follow other related articles on the PHP Chinese website!