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 git.master, git.master_jit, rfc.property-hooks
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

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
230.1 ms | 406 KiB | 5 Q