PHP 7 Cool Features
We are going to discuss some php7 cool features that make our coding life fun and easier.
The following are some of the cool PHP 7 features:
1-Scalar type declarations
2-Nullable types
3-Null coalescing operator
4-Spaceship operator
5-Constant arrays using define()
1-Scalar type declarations:
With scalar type declarations we can force a function to use certain types of parameters at call time. If not the function will throw a fatal error.
Let’s take an example of the below function that adds product quantity in a shopping cart.
// Coercive mode
function addQuantity(int $item1, int $item2)
{
return $item1 + $item2;
}addQuantity(6, 5.4);
//output int(11)
By declaring Strict Type it will throw a Fatal error
// Strict mode
declare(strict_types=1);
function addQuantity(int $item1, int $item2)
{
return $item1 + $item2;
}addQuantity(6, 5.4);
//output<b>Fatal error</b>: Uncaught TypeError: Argument 2 passed to addQuantity() must be of the type integer, float given
2-Nullable types: ?int
This feature is an addition to return type declaration. In the first release of PHP 7 the return type declaration, was made possible.
<?phpfunction add($a, $b) : float
{
return $a + $b;
}
This function will always output a float.
But usually, a function may return null
too. So nullable type is handy in that case.
<?phpfunction getQuantity() : ?int
{
return $this->quantity? $this->quantity:null; // ok
}
3-Null coalescing operator: ??
As per php.net changelog.
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.
// get id if exist.
$id = $_GET['id'] ?? null;// This is equivalent to:
$id = isset($_GET['id']) ? $_GET['id'] : null;// can be chained: return first defined value
$id = $_GET['id'] ?? $_POST['id'] ?? null;
4-Spaceship operator : <=>
The spaceship operator is used for comparing two expressions. It is represented like this <=>. It is used to compare two expressions and return -1, 0, 1 when one variable is less than, equal to, or greater than, as compared to the other variable.
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
5-Constant arrays using define():
Array constants can now be defined with define(). In PHP 5.6, they could only be defined with const.
define('DEVELOPER_NAME', array('Mobeen', 'Sarwar'));echo DEVELOPER_NAME[1]; // outputs "Mobeen"