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

No PhpWord assigned.

Error message

No PhpWord assigned.

What it means

AbstractWriter::getPhpWord() returns the PhpWord document assigned to the writer. Writers require a document to serialize; if none was set (via constructor or setPhpWord()) the writer has nothing to write and throws. It is an internal state guard protecting all write operations.

Solutions

  1. Pass the PhpWord instance to the writer's constructor.
  2. Call setPhpWord($phpWord) on the writer before using it.
  3. Prefer IOFactory::createWriter($phpWord, 'WriterName') so assignment is never missed.
  4. Check custom factory/DI code to ensure it forwards the document argument.

Example fix

// before
$writer = new \PhpOffice\PhpWord\Writer\ODText();
$writer->save('doc.odt'); // No PhpWord assigned
// after
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$writer = new \PhpOffice\PhpWord\Writer\ODText($phpWord);
$writer->save('doc.odt');
Defensive patterns

Strategy: type-guard

Validate before calling

function writerHasDocument(\PhpOffice\PhpWord\Writer\WriterInterface $writer): bool {
    $ref = new ReflectionProperty(get_class($writer), 'phpWord');
    $ref->setAccessible(true);
    return $ref->getValue($writer) !== null;
}

Try / catch

try {
    $writer->save($path);
} catch (\PhpOffice\PhpWord\Exception\Exception $e) {
    if ($e->getMessage() === 'No PhpWord assigned.') {
        $writer->setPhpWord($phpWord);
        $writer->save($path);
    } else { throw $e; }
}

Prevention

When it happens

Trigger: Instantiating a writer directly (e.g. new ODText()) without passing a PhpWord instance, or clearing the phpWord property before calling getContent()/save()/addNotes()/addComments().

Common situations: Custom code creating writers via reflection or DI containers that skip the constructor argument; partial mock/factory setups; calling writer methods before IOFactory::createWriter($phpWord, ...) completed assignment.

Related errors


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

Appendix: source

Thrown at src/PhpWord/Writer/AbstractWriter.php:108

    /**
     * Temporary file name.
     *
     * @var string
     */
    private $tempFilename;

    /**
     * Get PhpWord object.
     *
     * @return PhpWord
     */
    public function getPhpWord()
    {
        if (null !== $this->phpWord) {
            return $this->phpWord;
        }

        throw new Exception('No PhpWord assigned.');
    }

    /**
     * Set PhpWord object.
     *
     * @return self
     */
    public function setPhpWord(?PhpWord $phpWord = null)
    {
        $this->phpWord = $phpWord;

        return $this;
    }

    /**
     * Get writer part.
     *
     * @param string $partName Writer part name

View on GitHub (pinned to aef95c0415)