Created
December 4, 2015 09:11
-
-
Save nexpr/e7108f3eec2074a84d1b 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 InputGetter{ | |
function __get($key){ | |
return null; | |
} | |
function __construct($array){ | |
foreach($array as $key => $val){ | |
$this->$key = $val; | |
} | |
} | |
function get($key, $default = null){ | |
return property_exists($this, $key) ? $this->$key : $default; | |
} | |
function getAs($key, $type, $default = null){ | |
$val = $this->get($key, $default); | |
if(is_callable($type)){ | |
return call_user_func($type, $val); | |
}else{ | |
switch(strtolower($type)){ | |
case "int": | |
case "integer": | |
return (int)$val; | |
case "string": | |
case "str": | |
return (string)$val; | |
case "bool": | |
case "boolean": | |
return (bool)$val; | |
case "float": | |
case "double": | |
return (float)$val; | |
default: | |
return $val; | |
} | |
} | |
} | |
} |
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
$p = new InputGetter([ | |
"a" => 1, | |
"b" => "abc", | |
"c" => "9", | |
"d" => 0, | |
"e" => "1,2,3,4,5", | |
"f" => null, | |
]); | |
var_dump( | |
$p->a, // 1 | |
$p->d, // 0 | |
$p->f, // NULL | |
$p->z, // NULL | |
$p->get("a"), // 1 | |
$p->get("b"), // "abc" | |
$p->get("f", "default value"), // NULL | |
$p->get("z", "default value"), // "default value" | |
$p->getAs("a", "str"), // "1" | |
$p->getAs("b", "float"), // 0 | |
$p->getAs("c", "int"), // 9 | |
$p->getAs("d", "bool"), // false | |
$p->getAs("b", "foo"), // "abc" | |
$p->getAs("c", "sqrt"), // 3 | |
$p->getAs("z", "boolean", "default value"), // true | |
$p->getAs("e", function($e){ | |
return explode(",", $e); | |
}) // ["1","2","3","4","5"] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment