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 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 yield into 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 yield with plain assignments.

Changed Behavior

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