-
-
Save Crell/7e9dc30b1979750b6701a7246546ba2b to your computer and use it in GitHub Desktop.
Cloning with arguments
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 | |
class Point { | |
public initonly int $area; | |
public function __construct( | |
public initonly int $x, | |
public initonly int $y, | |
private initonly string $label, | |
) { | |
$this->area = $this->x * $this->y; | |
} | |
// This is super clumsy. | |
public function __clone(?int $x = null, ?int $y = null, ?string $label = null) { | |
if ($x) $this->x = $x; | |
if ($y) $this->y = $y; | |
if ($label) $this->label = $label; | |
$this->area = $this->x * $this->y; | |
} | |
// This is also super clumsy. | |
public function __clone(...$args) { | |
foreach ($args as $k => $v) { | |
if (in_array(needle: $key, haystack: ['x', 'y', 'label']) { | |
$this->k = $v; | |
} | |
} | |
if ($x) $this->x = $x; | |
if ($y) $this->y = $y; | |
if ($label) $this->label = $label; | |
$this->area = $this->x * $this->y; | |
} | |
public function label() { return $this->label; } | |
public function withLabel(string $label) { return clone($this, label: $label); } | |
} | |
$p1 = new Point(4, 5, "Mine"); | |
$p2 = clone($p1, x: 10); | |
$p3 = $p2->withLabel("Yours"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment