Last active
December 3, 2015 15:07
-
-
Save rightgo09/75feb07f2b76b4b83b4e to your computer and use it in GitHub Desktop.
This file contains 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 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