Skip to content

Instantly share code, notes, and snippets.

@hgraca
Last active July 6, 2020 13:55
Show Gist options
  • Save hgraca/2c5c1bd347e6cb7b6594ac30a1b45501 to your computer and use it in GitHub Desktop.
Save hgraca/2c5c1bd347e6cb7b6594ac30a1b45501 to your computer and use it in GitHub Desktop.
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