- var_dump: documentation ( source)
- array_splice: documentation ( source)
- array_merge: documentation ( source)
<?php
class Foo {
public function __construct(public readonly string $name) {}
}
class FancyArray {
public function __construct(public readonly array $array = []) {}
public function addElement(mixed $element): self {
if (false === $element instanceof Foo) {
throw new Exception("GOVNYAK!!!");
}
return new self(array_merge($this->array, [$element]));
}
public function removeElementByIndex(mixed $index): self {
return new self(array_splice(...[$this->array, $index, 1]));
}
}
$array = new FancyArray([new Foo('a'), new Foo('b')]);
$modifiedArray = $array->removeElementByIndex(1)
->addElement(new Foo('c'))
->addElement(new Foo('d'));
var_dump($array);
var_dump($modifiedArray);