On 3/12/2017 6:16 PM, Michael Vostrikov wrote:
> No, thanks) I don't have real problem. I know some problems with usual
> inheritance and try to suggest the tool to solve them. Problems which are
> mostly kinds of Rectangle-Square problem, and where is some restrictions in
> derived types.
>
As I said already, there is no problem if you just change the direction
of the inheritance.
class Square {
private $x;
private $y;
private $w;
public function __construct(int $x, int $y, int $w) {
$this->x = $x;
$this->y = $y;
$this->w = $w;
}
public function draw(Canvas $canvas): void { }
}
class Rectangle extends Square {
private $h;
public function __construct(int $x, int $y, int $w, int $h) {
parent::__construct($x, $y, $w);
$this->height = $h;
}
public function draw(Canvas $canvas): void { }
}
If you want to ensure that you always get a Square if width and height
match, no problem either.
class Square {
private $x;
private $y;
private $w;
private $h;
final protected function __construct(
int $x, int $y, int $w, int $h
) {
$this->x = $x;
$this->y = $y;
$this->w = $w;
$this->h = $h;
}
public static function new(int $x, int $y, int $w): self {
return new self($x, $y, $w, $w);
}
public function draw(Canvas $canvas): void { }
}
class Rectangle extends Square {
public static function new(
int $x, int $y, int $w, ?int $h = null
): parent {
if ($h === null || $w === $h) {
return new parent($x, $y, $w, $w);
}
return new self($x, $y, $w, $h);
}
}
Added bonus here is the fact that we disabled the possibility for
multiple constructor invocations, and are enforcing constructor argument
invariants (which PHP does not).
--
Richard "Fleshgrinder" Fussenegger
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php