How can PHP magic methods like __sleep and __wakeup be utilized for object serialization and deserialization?

When serializing objects in PHP, the __sleep magic method can be used to specify which object properties should be serialized. On the other hand, the __wakeup magic method can be used during deserialization to reinitialize object properties. By utilizing these magic methods, we can have more control over the serialization and deserialization process.

class MyClass {
    public $name;
    public $age;

    public function __sleep() {
        return ['name']; // Only serialize the 'name' property
    }

    public function __wakeup() {
        $this->age = 30; // Set a default value for 'age' during deserialization
    }
}

$obj = new MyClass();
$obj->name = 'John';
$obj->age = 25;

$serialized = serialize($obj);
$unserialized = unserialize($serialized);

var_dump($unserialized);