Skip to content

Instantly share code, notes, and snippets.

@Leko
Created November 5, 2015 07:45
Show Gist options
  • Save Leko/70cf6d48669c3c252f76 to your computer and use it in GitHub Desktop.
Save Leko/70cf6d48669c3c252f76 to your computer and use it in GitHub Desktop.
集合操作、したいやん?
<?php
class Invoker implements ArrayAccess {
private $targets;
public function __construct(array $targets) {
$this->targets = $targets;
}
public function __call($method, array $args) {
$results = array();
foreach($this->targets as $target) {
$results[] = call_user_func_array(array($target, $method), $args);
}
return $results;
}
public function offsetExists($offset) {
return isset($this->targets[$offset]);
}
public function offsetGet($offset) {
return $this->targets[$offset];
}
public function offsetSet($offset, $value ) {
$this->targets[$offset] = $value;
}
public function offsetUnset($offset) {
unset($this->targets[$offset]);
}
}
class Hoge {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
$list = new Invoker(array(
new Hoge('John'),
new Hoge('Bob'),
new Hoge('Ryan'),
new Hoge('Tom'),
));
var_dump($list->getName());
var_dump($list->getName()[0]);
var_dump($list[0]->getName());
// array(4) {
// [0]=>
// string(4) "John"
// [1]=>
// string(3) "Bob"
// [2]=>
// string(4) "Ryan"
// [3]=>
// string(3) "Tom"
// }
// string(4) "John"
// string(4) "John"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment