Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Support TypedArrayObject in php
<?php
//Tinker away!
Class YourClassName
{
public string $name;
}
abstract class TypedArrayObject extends ArrayObject
{
abstract public function className(): string;
public function __construct(array $array = [])
{
if(!empty($array) && count(array_filter($array, function ($entry) {
$className = $this->className();
return !($entry instanceof $className);
})) > 0) {
throw new \InvalidArgumentException('Value must be an instance of '.(string) $this->className());
}
parent::__construct($array, \ArrayObject::ARRAY_AS_PROPS);
}
public function offsetSet($key, $value): void
{
if (!($value instanceof YourClassName)) {
throw new \InvalidArgumentException('Value must be an instance of YourClassName');
}
parent::offsetSet($key, $value);
}
}
Class ArrayOfYourClassName extends TypedArrayObject
{
public function className(): string
{
return YourClassName::class;
}
}
Class AnotherClassWhereImplementingArrayOfClassA
{
public ArrayOfYourClassName $arrayOfClassA;
}
// Valid Case
$a = new YourClassName();
$a->name = "John Doe";
$b = new AnotherClassWhereImplementingArrayOfClassA();
// style one
$b->arrayOfClassA = new ArrayOfYourClassName([$a]);
// style two
$c = new ArrayOfYourClassName();
$c[] = $a;
$b->arrayOfClassA = $c;
var_dump($b->arrayOfClassA[0]->name);
// Invalid Case
$a = new YourClassName();
$a->name = "John Doe";
$b = new AnotherClassWhereImplementingArrayOfClassA();
// style one
$b->arrayOfClassA = new ArrayOfYourClassName([$a, "ok"]);
// style two
$c = new ArrayOfYourClassName();
$c[] = $a;
$c[] = "ok";
$b->arrayOfClassA = $c;
var_dump($b->arrayOfClassA[0]->name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment