Re: Re: RFC: short and inner classes

From: Date: Mon, 24 Mar 2025 09:20:03 +0000
Subject: Re: Re: RFC: short and inner classes
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-126921@lists.php.net to get a copy of this message
On Sun, Mar 23, 2025 at 5:20 PM Larry Garfield <larry@garfieldtech.com> 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

« previous php.internals (#126921) next »