In PHP, the __sleep magic method is used in the context of object serialization. When an object is about to be serialized using functions like serialize(), PHP automatically checks if the class of the object has a __sleep method. If the __sleep method is defined, it is called before the serialization process.
<!DOCTYPE html>
<html><body>
<?php
class MyClass {
public $data1;
public $data2;
public function __construct($data1, $data2) {
$this->data1 = $data1;
$this->data2 = $data2;
}
public function __sleep() {
// Returning an array of property names to be serialized
return ['data1'];
}
}
$obj = new MyClass('value1', 'value2');
// Serialize the object
$serialized = serialize($obj);
var_dump($serialized );
// $serialized now contains the serialized representation of the object,
// and only the properties specified in __sleep will be included in the serialization.
?>
</body>
</html>
Output
string(43) "O:7:"MyClass":1:{s:5:"data1";s:6:"value1";}"
Comments
Post a Comment