Skip to content

Instantly share code, notes, and snippets.

@ahungry
Created January 23, 2016 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahungry/a60d47e1d5802ae91737 to your computer and use it in GitHub Desktop.
Save ahungry/a60d47e1d5802ae91737 to your computer and use it in GitHub Desktop.
Safely get post data or defaults
<?php
function post($key, $default = '')
{
return isset($_POST[$key]) ? $_POST[$key] : $default;
}
$name = post('name', 'Jon Smith');
@ahungry
Copy link
Author

ahungry commented Jan 23, 2016

Can also use in this fashion:

<?php

$_POST['name'] = 'Frank';
$_POST['age'] = 33;

function post($key, $default = '???')
{
  return isset($_POST[$key]) ? $_POST[$key] : $default;
}

list($name, $age, $job) = array_map('post', ['name', 'age', 'job']);

printf('%s is %s and works as a %s', $name, $age, $job);

@ahungry
Copy link
Author

ahungry commented Jan 23, 2016

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