I wonder if I should write a function for a specific problem (e.g. function specific()) or if I should give this piece of code into one php script and call require 'specific.php' when needed?
The specific problem I’m talking is about processing a filled form requested via POST and then redirecting the browser because of the PRG (Post/Redirect/Get) pattern (which includes, that exit will be called and the code isn’t continued after the require respectively function call). The code for processing the request is needed in two scripts. Consider following code:
somePage.php
require 'process_form_fnc.php'; // for Variant 2
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// process filled form
require 'process_form.php'; // Variant 1
process_form_fnc(); // or Variant 2
}
Would you choose the function or the require variant (and why)?
Using
requireto insert arbitrary code blocks at the current location is a bad hackish (even though not uncommon). I would always prefer to keep my code in functions.You can find similar discussions for C (
#includearbitrary code snippets vs. functions), with almost the same arguments and an equally clear consensus.