Created
January 18, 2016 08:18
-
-
Save bernik/85c08a703bea3f32c93b to your computer and use it in GitHub Desktop.
array_of realization in php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class User { | |
public | |
$name, | |
$lastName; | |
public function __construct($name, $lastName) { | |
$this->name = $name; | |
$this->lastName = $lastName; | |
} | |
} | |
function array_of ($typename, $input = []) { | |
$name = ucfirst(strtolower($typename)); | |
$containerClassName = 'ArrayOf'.ucfirst(strtolower($typename)); | |
if (!class_exists($containerClassName)) { | |
create_container_class($name); | |
} | |
return new $containerClassName($input); | |
} | |
function create_container_class ($type) { | |
eval('class ArrayOf'.$type.' extends ArrayObject { | |
public function __construct ($input = [], $flags = 0, $iterator_class = "ArrayIterator") { | |
if ($input instanceof '.$type.') $input = [$input]; | |
if (!is_array($input)) throw new InvalidArgumentException("bad input"); | |
foreach ($input as $i) if (!($i instanceof '.$type.')) throw new InvalidArgumentException("bad element"); | |
return parent::__construct($input, $flags, $iterator_class); | |
} | |
public function offsetSet ($k, $v) { | |
if ($v instanceof User) return parent::offsetSet($k, $v); | |
throw new InvalidArgumentException("bad user"); | |
} | |
}'); | |
} | |
function names (ArrayOfUser $users) { return array_map(function ($u) { return $u->name; }, $users->getArrayCopy()); } | |
$arr = array_of ('user'); | |
$arr[] = new User('foo', 'last foo'); | |
$arr[] = new User('bar', 'last bar'); | |
$arr2 = array_of ('user', [ | |
new User(1,1), | |
new User(2,2)]); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment