Skip to content

Instantly share code, notes, and snippets.

@bernik
Created January 18, 2016 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bernik/85c08a703bea3f32c93b to your computer and use it in GitHub Desktop.
Save bernik/85c08a703bea3f32c93b to your computer and use it in GitHub Desktop.
array_of realization in php
<?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