Refactoring: Getting rid of an optional variable for a function
Here's the situation; below is a piece of PHP code which is frequently reused.
if (! isset($_REQUEST['process_form'])
{
// render form
echo "<form>";
// snipped
// important bit! Remember which id we are processing
echo "<input hidden='id' value='$id'>";
// snipped
} else {
// process the form
}
I wish to encapsulate this into a function, akin t开发者_Go百科o
class ProcessForm() {
function execute(array $request, $id) { };
}
The issue here is; the $id parameter is only needed when rendering the form. When processing the form after a user input or through an AJAX handler, I don't need the $id at all.
How could I refactor to get rid of the optional variable $id?
Optional parameters in PHP works like so
function example($id = NULL)
{
if(is_null($id))
echo '$id was omitted';
}
精彩评论