开发者

Refactoring: Getting rid of an optional variable for a function

开发者 https://www.devze.com 2023-01-19 02:10 出处:网络
Here\'s the situation; below is a piece of PHP code which is frequently reused. if (! isset($_REQUEST[\'process_form\'])

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';
}
0

精彩评论

暂无评论...
验证码 换一张
取 消