Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Making a destructor a Generator is deprecated

Description

Using yield anywhere in the body of __destruct() turns it into a Generator function. A Generator only starts executing once something iterates it, but nothing iterates the return value of a destructor: PHP just calls it during garbage collection and discards the result. As a consequence, the body of such a destructor never actually runs, silently skipping any cleanup code it contains.

Since this pattern is virtually always a mistake, PHP 8.6 deprecates making a destructor a Generator.

Example

<?php

class X {
    public function __destruct() {
        yield 1;
    }
}

$x = new X;
unset($x);

?>

Literal Examples

  • Making a destructor a Generator is deprecated

Alternatives

  • Move the code that uses yield into a separate, regular method that __destruct() calls directly.
  • If the destructor only needs to release resources, replace yield with plain statements.

Changed Behavior

This error may appear following an evolution in behavior, in previous versions. See destructorAsGenerator