I'm updating a bunch of PHP code that relies on register_globals
and uses request data globally. In the process of fixing/updating I spend a lot of time writing code that looks like:
<?php
$x = isset($_REQUEST['x']) ? $_REQUEST['x'] : $xdefault; // other times loaded from $_GET['x'] or $_POST['x']
$abc = isset($_REQUEST['abc']) ? $_REQUEST['abc'] : $abcdefault;
?>
I've been toying with the idea of using something like:
<?php
function _export(&$source, &$defaults) {
return array_merge($defaults, array_intersect_key($source, $defaults));
}
// old code essentially uses $_REQUEST, but I could point this at $_POST
// $_GET or a db query in the future
$defaults = array (
'x' => $xdefault,
'abc' => $abcdefault,
);
$options = _export($_GET, $defaults);
extract($options); //export if needed until global code can be fixed
?>
The benefits being:
- It's easier (I feel) to read array syntax compared to a list of ternary
issets()
assignments - The defaults array acts as a whitelist
- The defaults array can be used to document the expected or required inputs
Are there any disadvantages or possible improvements to this approach? I would name _export()
something different.
array_interset_key
doesn't exist (do you meanarray_intersect_key
?), I'm not aware of anyexport
function, and$result
doesn't exist (do you mean$options
?). It's also not completely clear to me what you mean by$xdefault; // or $_GET, $_POST
. Can you add a bit more context? \$\endgroup\$_export
function should return the result of the array merge, right? \$\endgroup\$