A Point Value Object
<?php | |
final class Point | |
{ | |
private int $x; | |
private int $y; | |
public function __construct(int $x, int $y) | |
{ | |
$this->x = $x; | |
$this->y = $y; | |
} | |
public function add(self $point): self | |
{ | |
return new Point($this->x + $point->x, $this->y + $point->y); | |
} | |
public function equals(self $point): bool | |
{ | |
return ($this->x === $point->x) && ($this->y === $point->y); | |
} | |
public function __toString(): string | |
{ | |
return "({$this->x}, {$this->y})"; | |
} | |
} | |
$p1 = new Point(1,1); | |
$p2 = new Point(1,-3); | |
$p3 = new Point(1,1); | |
$p4 = $p1->add($p2); | |
echo $p4 . "\n"; // (2, -2) | |
echo ($p1->equals($p4) ? 'equal' : 'different') . "\n"; // different | |
echo ($p1->equals($p2) ? 'equal' : 'different') . "\n"; // different | |
echo ($p1->equals($p3) ? 'equal' : 'different') . "\n"; // equal |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment