Refactoring to null coalescing operators In this refactoring we refactor isset to the null coalescing operator and expand it with the null coalescing assignment operator https://www.php.net
requires: php 7.0.0

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand.

Original code



        // Fetches the value of $_GET['status']
        // and returns 'no status defined' if it does not exist.

        $status = isset($_GET['status']) ? $_GET['status'] : 'no status defined';

        

Refactored code



        // Example 1 : With the null coalescing operator
        $status $_GET['status'] ?? 'no status defined';

        
$this->showOutput(__FUNCTION__ " - example 1"$status);

        
// Example 2 : With the null coalescing assignment operator it can even be more simplified:
        
$_GET['status'] ??= 'no status defined';

        

Here is the output of the code

This is the output of original

no status defined

This is the output of refactor - example 1

no status defined

This is the output of refactor - example 2

no status defined

Want to learn more from LLoadout ?

LLoadout is your loadout for Laravel, helping you kickstart your development process. Besides this refactoring site we also make some cool packages and video tutorials !

Go to LLoadout on github