Last active
July 6, 2020 13:55
-
-
Save hgraca/2c5c1bd347e6cb7b6594ac30a1b45501 to your computer and use it in GitHub Desktop.
A Point Value Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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