Making a constructor a Generator is deprecated
Description
Using yield anywhere in the body of __construct() turns it into a Generator function. Because a Generator’s body only starts running once it is iterated (and nothing iterates a constructor), the code inside such a constructor never runs when the object is created with new: initialization is silently skipped.
Since this pattern is virtually always a mistake, PHP 8.6 deprecates making a constructor a Generator.
Example
<?php
class X {
public function __construct() {
yield 1;
}
}
new X;
?>
Literal Examples
- Making a constructor a Generator is deprecated
Alternatives
- Move the code that uses
yieldinto a separate, regular method, and call it (or return its Generator) explicitly instead of relying on__construct(). - If the constructor only needs to assign properties, replace
yieldwith plain assignments.
Related error messages
- making-a-destructor-a-generator-is-deprecated
- returning-a-value-from-a-constructor-is-deprecated
- constructor-%s::%s()-cannot-declare-a-return-type
Related error messages
Changed Behavior
This error may appear following an evolution in behavior, in previous versions. See constructorAsGenerator