Skip to content

Instantly share code, notes, and snippets.

@Crell
Created November 29, 2020 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Crell/7e9dc30b1979750b6701a7246546ba2b to your computer and use it in GitHub Desktop.
Save Crell/7e9dc30b1979750b6701a7246546ba2b to your computer and use it in GitHub Desktop.
Cloning with arguments
<?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