phpserializationdomdocumentphp-8.1

PHP 8.1 DOMDocument serialization


I'm trying to make the following class compatible with native PHP serialization, specifically when running on PHP 8.1.

class SerializableDomDocument extends DOMDocument
{
    private $xmlData;

    public function __sleep(): array
    {
        $this->xmlData = $this->saveXML();
        return ['xmlData'];
    }

    public function __wakeup(): void
    {
        $this->loadXML($this->xmlData);
    }
}

It's all fine and dandy on lower PHP versions, but 8.1 yields Uncaught Exception: Serialization of 'SerializableDomDocument' is not allowed whenever such an object is attempted to be passed to serialize() function. Here's a sample of the code that would produce such an exception: https://3v4l.org/m8sgc.

I'm aware of the __serialize() / __unserialize() methods introduced in PHP 7.4, but using them doesn't seem to be helping either. The following piece of code results into the same exception as can be observed here: https://3v4l.org/ZU0P3.

class SerializableDomDocument extends DOMDocument
{
    public function __serialize(): array
    {
        return ['xmlData' => $this->saveXML()];
    }

    public function __unserialize(array $data): void
    {
        $this->loadXML($data['xmlData']);
    }
}

I'm quite baffled by this problem, and would really appreciate any hints. For the time being it seems like the only way forward would be to introduce an explicit normalizer/denormalizer, which would result in a breaking change in the codebase API. I'd like to avoid that.


Solution

  • This is no-longer an issue, and has been fixed for PHP ^8.1.25 || ^8.2.12 || ^8.3

    More details: