On Sun, Mar 23, 2025 at 5:20 PM Larry Garfield <[email protected]>
wrote:
>
> So, how would nested classes compare to fileprivate, in terms of ability
> to solve the problem space? As I understand it, the goal is:
>
> 1. Classes that can be instantiated only by the class that uses them.
> 2. But can be returned from that class to a caller and reused as
> appropriate.
>
I think the one other difference is that nested classes can access private
variables or their outer classes.
Example:
```
class Polygon {
private function __construct(private array $points) {}
public function getPoints(): array {
return $this->points;
}
public class Builder {
private array $points = [];
public function addPoint(Points $point): self {
$this->points[] = $point;
return $this;
}
public function build(): Polygon {
if (count($this->points) < 3) {
throw new InvalidArgumentException('A polygon must have at
least 3 points');
}
return new Polygon($this->points);
}
}
}
```
And it would be used like this:
```
$polygon = new Polygon::Builder()
->addPoint($point1)
->addPoint($point1)
->addPoint($point1)
->build();
```
With no way to create a Polygon otherwise, due to the private constructor.
-- Alex