Skip to content

Instantly share code, notes, and snippets.

@Shipu
Created August 3, 2022 14:41
Show Gist options
  • Save Shipu/b37a10fdf598e326a51e4f66c5c6fe1d to your computer and use it in GitHub Desktop.
Save Shipu/b37a10fdf598e326a51e4f66c5c6fe1d to your computer and use it in GitHub Desktop.
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