Skip to content

Instantly share code, notes, and snippets.

@rightgo09
Last active Dec 3, 2015
Embed
What would you like to do?
<?php
class ArrayOptionNoSuchElementException extends ErrorException {}
class ArrayOption
{
private $v;
public function __construct($v)
{
$this->v = $v;
}
public function __get($name)
{
if (is_array($this->v)) {
$v = array_key_exists($name, $this->v) ? $this->v[$name] : null;
}
else {
$v = $this->v;
}
return new self($v);
}
public function get()
{
if (is_null($this->v)) {
throw new ArrayOptionNoSuchElementException();
}
return $this->v;
}
public function getOrElse($default)
{
if (is_null($this->v)) {
return $default;
}
return $this->v;
}
}
//$xarr = new ArrayOption(['hoge' => ['fuga' => 'piyo']]);
//var_dump($xarr->hoge->get());
//var_dump($xarr->hoge->fuga->get());
//// var_dump($xarr->foo->get()); ArrayOptionError
//
//var_dump($xarr->hoge->getOrElse('nakatta'));
//var_dump($xarr->hoge->fuga->getOrElse('hogehoge'));
//var_dump($xarr->foo->getOrElse('nakatta'));
//
//foreach ($xarr->hoge->get() as $k => $v) {
// echo "\$k: $k, \$v: $v\n";
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment