Search

A Comparison of the abort, abort_if, and abort_unless Helper Functions

November 20, 2016 —John Koster

This article is a short comparison of the following application helper functions:

All three functions (abort, abort_if and abort_unless) can cause the execution of an application to stop. Each of them can cause the exact same end result, but the abort_if and abort_unless functions allow for the writing of code that reads easier and takes up less space. The following examples will all accomplish the same task to show the subtle differences in how each function is used.

The following examples assume that some $user object exists with the property admin. The example will check to make sure that the admin property is true. If not, the code will abort with a 401 (unauthorized access) error code.

1<?php
2 
3// Check to make sure that the user is
4// an administrator. If not, we will
5// abort the execution of the app.
6 
7// Using the `abort` function.
8if (!$user->admin) {
9 abort(401);
10}
11 
12// Using the `abort_if` function.
13abort_if(!$user->admin, 401);
14 
15// Using the `abort_unless` function.
16abort_unless($user->admin, 401);

Which function you decide to use largely depends on preference and the semantics of the variable names. For example, the abort_if function can make sense in the context of a subscription or credit card that might be expired:

1<?php
2 
3abort_if($subscription->expired, 401);
4abort_if($creditCard->expired, 401);

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.