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
yieldinto a separate, regular method that__destruct()calls directly. - If the destructor only needs to release resources, replace
yieldwith plain statements.
Related error messages
- making-a-constructor-a-generator-is-deprecated
- returning-a-value-from-a-destructor-is-deprecated
- destructors-cannot-declare-a-return-type
Related error messages
Changed Behavior
This error may appear following an evolution in behavior, in previous versions. See destructorAsGenerator