3v4l.org

run code in 300+ PHP versions simultaneously
<?php /* A very simple implementation of 'typed array', like this: $stringArray = new TypedArray('string'); and now only strings can be added to the above $stringArray. Works with objects as well. More examples below. */ class TypedArray extends \ArrayIterator { protected $type = ''; public function __construct(string $type, array $input = [], int $flags = 0){ $this->type = $type; parent::__construct($input, $flags); } /* Just an utility funciton. In case it's a scalar (like int), or array etc - returns that if it's an object, returns the name of the class. */ public function getTypeOrClassName($val){ $testType = gettype($val); if($testType === 'object'){ return get_class($val); } return $testType; } public function checkType($val){ return $this->getTypeOrClassName($val) === $this->type; } public function getType(){ return $this->type; } public function offsetSet($offset, $value) { if(!$this->checkType($value)){ throw new \InvalidArgumentException('This TypedArray accepts only "' . $this->type . '" type, "' . $this->getTypeOrClassName($value) . '" given'); } return parent::offsetSet($offset, $value); } } ////////////////////////////////////////////////////////////////////////////// //examples $stringArray = new TypedArray('string'); $stringArray []= 'first string'; $stringArray []= 'second string'; //$stringArray [] = 2;//won't work - exception thrown var_dump((array)$stringArray); //tests with objects as values class User{ public $name; public function __construct($name){ $this->name = $name; } } $userArray = new TypedArray(User::class); $userArray[]= new User('John'); //$userArray []= new \StdClass();//exception thrown echo $userArray[0]->name;
Output for 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.28, 8.4.1 - 8.4.14, 8.5.0
Deprecated: Return type of TypedArray::offsetSet($offset, $value) 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/kHocv on line 40 array(2) { [0]=> string(12) "first string" [1]=> string(13) "second string" } John
Output for 8.4.15
/bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.35' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.34' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15)
Process exited with code 1.
Output for 7.1.0 - 7.1.20, 7.2.0 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30
array(2) { [0]=> string(12) "first string" [1]=> string(13) "second string" } John

preferences:
266.89 ms | 410 KiB | 5 Q