PHP 7 cool new features

Hello all,

Today, I thought to give you a quick run through about cool new features in PHP 7. PHP 7 has been there for sometime but it is still worth paying some closer look at what it has to offer to the world of PHP development. In this post I will be giving few examples which are exclusively to PHP 7 and onwards. Please note that at the time I write this post PHP 7.2.5 is available to download.

Scalar type declarations

Type declaration tells the type of the arguments needs to be passed when calling a function. Available scalar types are class, self, callable, array, int, string, float, boolean and iterable. (The latter five was introduced as part of PHP 7).

declare(strict_types=1);
function getTotal(int ...$ints)
{
return array_sum($ints);
}

var_dump(getTotal(45, 85, 134));

The above will give you this,

int(264)

With the strict_types enabled if you call the same function by passing mixed type parameters like this,

var_dump(getTotal("45", '8', 134.4));

This will give you a TypeError,

Fatal error: Uncaught TypeError: Argument 1 passed to getTotal() must be of the type integer, string given, Next TypeError: Argument 2 passed to getTotal() must be of the type integer, string given, Next TypeError: Argument 3 passed to getTotal() must be of the type integer, float given. 

For additional information, the declaration of strict type is per file basis and it will affect function parameter types as well as function return types.

Return type declarations

Return type tells the type that is being returned upon calling a function. The available types are same as above.

declare(strict_types=1);
function getStockKeepingUnit() : string
{
return "123";
}

var_dump(getStockKeepingUnit());

The above will give you this,

string(3) "123"

However, with the strict_types enabled if you try to return something other than what’s declared in the return type you will get a TypeError,

declare(strict_types=1);
function getStockKeepingUnit() : string
{
return 123; //this returns an integer
}

var_dump(getStockKeepingUnit());

The above will give you following error,

Fatal error: Uncaught TypeError: Return value of getStockKeepingUnit() must be of the type string, integer returned.

Null coalescing operator

Null coalescoing operator (??) checks if something exists and not NULL. See the example below,

$test = array('firstName' => 'Anjana', 'lastName' => 'Silva');
$firstName = $test['firstName'] ?? 'Not given';
echo $firstName;

The above will give you,

Anjana

If we slightly change the condition to be this,

$test = array('firstName' => 'Anjana', 'lastName' => 'Silva');
$middleName = $test['middleName'] ?? 'Not given';
echo $middleName ;

Then the above will give you,

Not given

The above operator (??) is identical to following,

$firstName = isset($test['middleName']) ? $test['middleName'] : 'Not given';

Spaceship operator

Spaceship operator compares two expressions and returns -1, 0 and 1, respectively when the first operand is less than, equal and greater than the second operand. When comparing expressions you will need to take care of type comparison rules for both loose and strict comparisons.

echo 50 <=> 50;
echo 50 <=> 100;
echo 100 <=> 50;

The above will give you,

0
-1
1

Constant arrays using define

In PHP 7, you can define constant arrays using define. See an example below,

define('days', [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
]);

echo days[3];

The above will give you,

Thursday

Grouping Use statements

In PHP 7, you can group classes, constants and functions that are from the same namespace like this using a single use statement,

// Before PHP 7
use YourProject\Person;
use YourProject\Contact;
use YourProject\Organisation as Org;

use function YourProject\FunctionLists\getTotalHires;
use function YourProject\FunctionLists\getMaxHires;
use function YourProject\FunctionLists\getTotalExpenses;

use const YourProject\ConstantLists\HireType;
use const YourProject\ConstantLists\CarType;
use const YourProject\ConstantLists\FuelType;

// In PHP 7+, you can do like this
use YourProject\{Person, Contact, Organisation as Org};
use function YourProject\FunctionLists\{getTotalHires, getMaxHires, getTotalExpenses};
use const YourProject\ConstantLists\{HireType, CarType, FuelType};

Handling multiple exceptions in the same Catch block

This is one my favourites. Handling multiple exceptions in the same catch block is super cool. From PHP 7.1+ onwards you can do this. See this example below,

class AnjanaException extends Exception {
    public function __construct($message = null, $code = 0) {
       echo $message;
    }
}
 
class SilvaException extends Exception {
    public function __construct($message = null, $code = 0) {
        echo $message;
    }
}
 
class SomeNastyException extends Exception {
    public function __construct($message = null, $code = 0) {
        echo $message;
    }
}

try {
    throw new AnjanaException('This is a Anjana exception');
	throw new SilvaException('This is a Silva exception');
	throw new SomeNastyException('This is some nasty exception');
}
catch(AnjanaException | SilvaException | SomeNastyException $e) {
    
}

I hope you enjoyed my post about new features in PHP 7. These are just a few new features shipped with PHP 7 and onwards. So, keep learning and enjoy the beautiful PHP 7 :). Leave a your comments / suggestions in the comments section below. Thank you for reading.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *