Created
January 23, 2016 06:19
-
-
Save ahungry/a60d47e1d5802ae91737 to your computer and use it in GitHub Desktop.
Safely get post data or defaults
This file contains hidden or 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 | |
function post($key, $default = '') | |
{ | |
return isset($_POST[$key]) ? $_POST[$key] : $default; | |
} | |
$name = post('name', 'Jon Smith'); |
With magical class:
// Magical class, ooooooaaaaaaaahhhhhh
class Param
{
public function __call($fn, $args) {
$global = '_' . strtoupper($fn);
$global = isset($$global) ?: $fn;
global $$global;
$args = $args + [null, '???'];
list($key, $default) = $args;
return isset($$global[$key]) ? $$global[$key] : $default;
}
}
$p = new Param();
list($name, $age) = array_map([$p, 'post'], ['name', 'age']);
list($job, $years) = array_map([$p, 'get'], ['job', 'years']);
printf('%s is %s and works as a %s for %s years', $name, $age, $job, $years);
$name = $p->post('name', 'Jon Smith');
$job = $p->get('job', 'Something');
$fail = $p->fail('hello', 'world');
echo $fail; // Will say 'world'
$puppies = ['boy' => 'fido', 'girl' => 'sparky'];
$boyDog = $p->puppies('boy');
$girlDog = $p->puppies('girl');
printf('My dogs are %s and %s', $boyDog, $girlDog);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can also use in this fashion: