The 5th Annual China PHP Conference

Voting

Please answer this simple SPAM challenge: max(eight, four)?
(Example: nine)

The Note You're Voting On

moochm@gmail
9 years ago
When using a php script like a remote function call, I find something like this useful for setting default parameters.

<?php
/**
/* combine _GET _POST _COOKIE variables with provided default values
/* defaults - associative array of default values
/* overwrite - if true, write result to _REQUEST superglobal
/* super_globals - array of super globals to fetch values from
**/
function get_params($defaults = null, $overwrite = false, $super_globals = array('_GET', '_POST', '_COOKIE'))
{
   
$ret = array();

   
// fetch values from request
   
foreach($super_globals as $sg)
        foreach(
$GLOBALS[$sg] as $k=>$v)
           
$ret[$k] = $v;

   
// apply defaults for missing parameters
   
if($defaults) foreach($defaults as $k=>$v)
        if(!isset(
$ret[$k]))
           
$ret[$k] = $v;

    if(
$overwrite)
       
$_REQUEST = $ret;

    return
$ret;
}

// Example: page.php?style=modern

$argv = get_params(array('id'=>42, 'style'=>'medieval'));

// $argv['id'] = 42
// $argv['style'] = 'modern'

?>

<< Back to user notes page

To Top