What is a Wrapper Function? + a Basic Example

Wikipedia defines wrapper functions this way:

A wrapper function is a subroutine in a software library or a computer program whose main purpose is to call a second subroutine or a system call with little or no additional computation.

So basically, a wrapper function is simply a function used to call another function or multiple functions. This might be for security reasons (through APIs), or it could just be for the convenience of only having one instance of some code to update.

Real-Life Example

Let’s say you have a bunch of HTML/CSS landing pages. They all use the same form to subscribe to your mailing list, but some of them may have extra fields like hidden inputs, a phone field, address fields, etc. Ideally you would have one file that houses your HTML form so that it’s only one file to change if you need to. If you were to throw the form code in an include file, every landing page would have the same inputs. The wrapper function comes in to play by creating a function that echoes or returns the form code with any additional inputs being passed to the function.

Landing Page A

// Include the file that defines the function.
include("form.php");
...
// Declare the argument to pass to the function.
$extra_inputs = "<input type='hidden' name='source' value='AdWords Landing Page'>";
echo_form($extra_inputs); // Will echo out standard form along with the $extra_inputs defined above.

Landing Page B

// Include the file that defines the function.
include("form.php");
...
// Declare the argument to pass to the function.
$extra_inputs = "<input type='hidden' name='source' value='Facebook Ads Landing Page'>
<input type='text' name='phone'>";
echo_form($extra_inputs); // Will echo out standard form along with the $extra_inputs defined above.

Included File With a Wrapper Function

function echo_form($extra_inputs = "") {
    echo "<form action='your-signup-action' method='post'>
    <!-- All your standard inputs for your form go here. -->
    <input type='text' name='first-name'>
    <input type='text' name='last-name'>
    <input type='email' name='email'>";
    if ($extra_inputs != "") {
        echo $extra_inputs;
    }
    echo "<input type='submit' value='Sign Up!'>
    </form>";
}

So using a wrapper function for a scenario like this allows you more flexibility than simply having the form code in an include file. You could even take this a step further and add a parameter to specify different call-to-actions on the submit button. Then this function can be used for A/B testing different required fields or different CTAs.

Further Reading

Category: PHP