Skip to content

34: Move Results and Generators Out of Object Lifecycles

Create an object through a factory and iterate its data through an ordinary method. A constructor or destructor that returns a value or acts as a generator now triggers a deprecation.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable constructor-destructor-returns.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/34-constructor-destructor-returns/constructor-destructor-returns.php
constructor-destructor-returns.php
<?php
declare(strict_types=1);
final class Labels
{
private function __construct(private array $labels)
{
}
public static function fromCsv(string $csv): self
{
return new self(explode(',', $csv));
}
public function values(): Generator
{
foreach ($this->labels as $label) {
yield trim($label);
}
}
}
foreach (Labels::fromCsv('tea, coffee')->values() as $label) {
echo $label, PHP_EOL;
}
tea
coffee

Initialize state in __construct(). Return the new object from a factory and put yield in a separate method so callers can drive iteration. A destructor is for cleanup and can use a bare return; for an early exit.

Add another label to the factory input and confirm it appears only when you iterate the generator.

Continue with Return an Array from __debugInfo().