PHPOffice/PHPWord · error · PhpOffice\PhpWord\Exception\Exception

No parent WriterInterface assigned.

Error message

No parent WriterInterface assigned.

What it means

HTML writer parts (AbstractPart subclasses) need a reference to their parent writer to access styles, settings, and the document. getParentWriter() throws when the parentWriter property was never injected, meaning the part cannot resolve dependencies during write().

Solutions

  1. Call setParentWriter($htmlWriter) on the part before writing.
  2. Let the standard HTML writer construct and wire its parts instead of instantiating them manually.
  3. In subclasses, ensure the parent writer is passed through when parts are created.
  4. Guard custom factories with a null check on parentWriter before invoking write.

Example fix

// before
$part = new \PhpOffice\PhpWord\Writer\HTML\Part\Body();
$html = $part->write(); // No parent WriterInterface assigned
// after
$writer = new \PhpOffice\PhpWord\Writer\HTML(new \PhpOffice\PhpWord\PhpWord());
$part = new \PhpOffice\PhpWord\Writer\HTML\Part\Body();
$part->setParentWriter($writer);
$html = $part->write();
Defensive patterns

Strategy: type-guard

Validate before calling

function partHasParent(\PhpOffice\PhpWord\Writer\HTML\Part\AbstractPart $part): bool {
    $ref = new ReflectionProperty(get_class($part), 'parentWriter');
    $ref->setAccessible(true);
    return $ref->getValue($part) !== null;
}

Try / catch

try {
    $html = $part->write();
} catch (\PhpOffice\PhpWord\Exception\Exception $e) {
    if ($e->getMessage() === 'No parent WriterInterface assigned.') {
        $part->setParentWriter($htmlWriter);
        $html = $part->write();
    } else { throw $e; }
}

Prevention

When it happens

Trigger: Instantiating an HTML part manually and calling write()/getElementStyle() without setParentWriter(); constructing parts in custom code that bypasses the HTML writer's wiring flow.

Common situations: Custom HTML export pipelines assembling parts manually; unit tests instantiating parts directly; overridden writer subclasses forgetting to propagate the parent writer to parts.

Related errors


AI-assisted analysis of PHPOffice/PHPWord@aef95c0415 (2026-09-14). Data as JSON: /api/errors/49a1515841c6eaf6. Report an issue: GitHub.

Appendix: source

Thrown at src/PhpWord/Writer/HTML/Part/AbstractPart.php:53

     * @return string
     */
    abstract public function write();

    public function setParentWriter(?HTML $writer = null): void
    {
        $this->parentWriter = $writer;
    }

    /**
     * @return HTML
     */
    public function getParentWriter()
    {
        if ($this->parentWriter !== null) {
            return $this->parentWriter;
        }

        throw new Exception('No parent WriterInterface assigned.');
    }
}

View on GitHub (pinned to aef95c0415)