How does the concept of object-oriented programming (OOP) in PHP play a role in resolving issues related to DOMDocument usage in constructors?

When using DOMDocument in constructors, the issue arises when trying to directly manipulate the DOMDocument object within the constructor. To resolve this, we can create a separate method within our class to handle the DOMDocument operations instead of directly manipulating it in the constructor.

<?php

class DocumentHandler {
    private $domDocument;

    public function __construct() {
        $this->domDocument = new DOMDocument();
    }

    public function loadDocument($xml) {
        $this->domDocument->loadXML($xml);
    }

    public function saveDocument($filename) {
        $this->domDocument->save($filename);
    }
}

// Example usage
$handler = new DocumentHandler();
$handler->loadDocument('<root><element>Example</element></root>');
$handler->saveDocument('example.xml');