<?php
final class TypedArray extends ArrayIterator
{
private $class;
public function __construct($class)
{
$this->class = $class;
parent::__construct(array());
}
public function offsetSet($index, $newValue)
{
if (!$newValue instanceof $this->class) {
throw new \InvalidArgumentException('Expected instance of ' . $this->class);
}
}
}
class A {}
$array = new TypedArray(A::class);
$array[] = new A;
$array['boo'] = new A;
foreach ($array as $key => $value) {
echo $key . ' -> ';
var_dump($value);
echo PHP_EOL;
}
$array[] = 'blah';
/* implements Iterator, ArrayAccess
{
private $class;
private $array;
public function __construct($class)
{
$this->class = $class;
$this->array = array();
}
public function current()
{
return current($this->array);
}
public function key()
{
return key($this->array);
}
public function next()
{
return next($this->array);
}
public function rewind()
{
return rewind($this->array);
}
} */
Deprecated: Return type of TypedArray::offsetSet($index, $newValue) should either be compatible with ArrayIterator::offsetSet(mixed $key, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /in/TWXI2 on line 14
Fatal error: Uncaught InvalidArgumentException: Expected instance of A in /in/TWXI2:17
Stack trace:
#0 /in/TWXI2(34): TypedArray->offsetSet(NULL, 'blah')
#1 {main}
thrown in /in/TWXI2 on line 17
Process exited with code 255.
Fatal error: Uncaught InvalidArgumentException: Expected instance of A in /in/TWXI2:17
Stack trace:
#0 /in/TWXI2(34): TypedArray->offsetSet(NULL, 'blah')
#1 {main}
thrown in /in/TWXI2 on line 17
Process exited with code 255.
Output for 5.5.0 - 5.5.38, 5.6.0 - 5.6.38
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Expected instance of A' in /in/TWXI2:17
Stack trace:
#0 /in/TWXI2(34): TypedArray->offsetSet(NULL, 'blah')
#1 {main}
thrown in /in/TWXI2 on line 17
Process exited with code 255.