Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering PHP 7

You're reading from   Mastering PHP 7 Design, configure, build, and test professional web applications

Arrow left icon
Product type Paperback
Published in Jun 2017
Publisher Packt
ISBN-13 9781785882814
Length 536 pages
Edition 1st Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Branko Ajzele Branko Ajzele
Author Profile Icon Branko Ajzele
Branko Ajzele
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Preface 1. The All New PHP FREE CHAPTER 2. Embracing Standards 3. Error Handling and Logging 4. Magic Behind Magic Methods 5. The Realm of CLI 6. Prominent OOP Features 7. Optimizing for High Performance 8. Going Serverless 9. Reactive Programming 10. Common Design Patterns 11. Building Services 12. Working with Databases 13. Resolving Dependencies 14. Working with Packages 15. Testing the Important Bits 16. Debugging, Tracing, and Profiling 17. Hosting, Provisioning, and Deployment

The null coalesce operator

Working with variables in PHP is quite easy. Variable declaration and initialization is done via a single expression. For example, the expression $user['name'] = 'John'; will automatically declare variable $user of type array and initialize that array with a single key name of value John.

Day-to-day development often includes checking for the existence of a variable value for various branching decisions, such as if ($user['name'] =='John') { … } else { … }. As we write our code ourselves, we tend to make sure that our code does not use non-declared variables and non-initialized array keys. There are cases, however, where variables come from outside, so we are not really in a position to guarantee their existence at runtime. Calling for $user['name'] when $user is not set, or is set but with keys other than name, will result in notice undefined index--name. Like any unexpected state in code, notices are bad, more so because they do not actually break your code, they allow it to execute further. When a notice occurs, unless we have the display_errors configuration set to true, and error reporting configured to show E_ALL, we would not even see the notice in the browser.

This is bad, as we might depend on the existence of variables and their values that are not there. This dependency might not even be handled in our code, and we would not even notice it because the code will continue to execute unless a specific variable check is put in place.

The PHP language has a certain number of predefined variables called superglobals, which we can use from any function, class, or file, regardless of the scope. The most used ones are probably $_POST and $_GET superglobals, which are used to fetch the data submitted via forms or URL parameters. Since we cannot guarantee the existence of $_GET['name'] in such cases, we need to check for it. Usually, this is done using the isset and empty functions in PHP, as shown in the following code block:

// #1
if (isset($_GET['name']) && !empty($_GET['name']))
{
$name = $_GET['name'];
}
else {
$name = 'N/A';
}

// #2
if (!empty($_GET['name']))
{
$name = $_GET['name'];
}
else {
$name = 'N/A';
}

// #3

$name = ((isset($_GET['name']) && !empty($_GET['name']))) ? $_GET['name'] : 'N/A';

// #4
$name = (!empty($_GET['name'])) ? $_GET['name'] : 'N/A';

The first example is the most robust one, as it uses both, the isset and empty functions. These functions are not the same, so it's important to understand what each of them does. The good thing about an empty function is that it will not trigger a notice if we try to pass it a variable that might not be set, such as $_GET['name']; it will simply return true or false. This makes the empty function a nice helper for most cases. However, even the fourth example, written via the use of the ternary operator, is somewhat robust.

PHP 7 introduced a new type of operator called the null coalesce (??) operator. It empowers us with the ability of writing shorter expressions. The following example demonstrates the elegance of its use:

$name = $_GET['name'] ?? 'N/A';

It returns the result of its first operand if it exists and is not null, or else its second operand. In other words, reading it from left to right, the first existing value, which is not null, is the value that will be returned.

You have been reading a chapter from
Mastering PHP 7
Published in: Jun 2017
Publisher: Packt
ISBN-13: 9781785882814
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime