Learn The top 5 Features of PHP 7.4 With Examples

PHP 7.4, the next PHP 7 minor release, has been released for General Availability as of November 28th, 2019. So it’s time for us to dive into some of the most exciting additions and new features that will have made PHP faster and more reliable.

New features in PHP 7.4

  • Null coalescing assignment operator
  • Arrow Functions
  • Typed Properties
  • Spread Operator in Array Expression
  • Numeric Literal Separator

1.Null coalescing assignment operator

Null coalescing is a new operator introduced in PHP 7. This operator returns its first operand if it is set and not NULL. Otherwise it will return its second operand.

Let’s take a look at the following example to see the difference

$username = $_GET['user'] ?? ‘nobody';


What this code does is pretty straightforward: it fetches the request parameter and sets a default value if it doesn’t exist. The meaning of that line is clear, but what if we had much longer variable names as in this example from the RFC?

$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';

In the long run, this code could be a bit difficult to maintain. So, aiming to help developers to write more intuitive code, this RFC proposes the introduction of the null coalescing assignment operator (??=). So, instead of writing the previous code, we could write the following:

$this->request->data['comments']['user_id'] ??= ‘value’;


If the value of the left-hand parameter is null, then the value of the right-hand parameter is used.
Note that, while the coalesce operator is a comparison operator, ??= is an assignment operator.

2.Arrow Functions

This is a feature that got accepted in April 2019 and loved by the PHP community. Arrow functions are extremely useful when writing callback functions (or closures, if you like). Before PHP 7.4, you had to use array_map as follows.

Consider the following example:

function cube($n){
	return ($n * $n * $n);
}
$a = [1, 2, 3, 4, 5];
$b = array_map('cube', $a);
print_r($b);

PHP 7.4 allows to use a more concise syntax, and the function above could be rewritten as follows:

$a = [1, 2, 3, 4, 5];
$b = array_map(fn($n) => $n * $n * $n, $a);
print_r($b);

Currently, anonymous functions (closures) can inherit variables defined in the parent scope thanks to the use language construct, as shown below:


$factor = 10;
$calc = function($num) use($factor){
	return $num * $factor;
};

But with PHP 7.4, variables defined in the parent scope are implicitly captured by value (implicit by-value scope binding). So we can write the whole function seen above on a single line:


$factor = 10;
$calc = fn($num) => $num * $factor;

The variable defined in the parent scope can be used in the arrow function exactly as if we were using use($var), and it’s not possible to modify a variable from the parent scope.

The new syntax is a great improvement to the language as it allows us to build more readable and maintainable code. We can also use parameter and return types, default values, variable-length argument lists (variadic functions), we can pass and return by reference, etc. Finally, short closures can also be used in class methods, and they can make use of the $this variable just like regular closures.

This RFC has been approved with 51 to 8 votes, so we can expect it to be part of PHP 7.4 additions.

3. Typed Properties (version 2.0)

Functions and class methods have already been available since PHP 5. You have seen it right?

function (int $age) {
//          ^^^
}

Since PHP 7.4, you can declare types for class properties. Here’s an example.


class MyMathClass { // <- don't get distracted
    public int $id;
    protected string $name;
    private ?int $age; // nullable types

    public static int $someStaticProp;

    private MyScienceClass $science;
    //      ^^^^^
    //      Using a class as the type       
}

All the PHP data types are allowed except void and callable.

One more thing to note is that there’s a new “Uninitialized state” (Source). If you run the following code,


class User {
    public int $id;
}
$user = new User;
var_dump($user -> id);

…what will be the result? Null? No. You’ll get an error message.

Fatal error: Uncaught Error: Typed property Foo::$bar must not be accessed before initialization

This means that there’s a new “uninitialized” state for properties introduced. And, the unset() function will work differently for types and untyped properties.

  • Types props – unset() will set the prop to uninitialized (similar to undefined in Javascript).
  • Untyped props – unset() will set prop to null.

4. Spread Operator in Array Expression

Available since PHP 5.6, argument unpacking is a syntax for unpacking arrays and Traversables into argument lists. To unpack an array or a Traversable, it has to be prepended by … (3 dots), as shown in the following example:


function dumpNames(...$names) {
    var_dump($names);
}
dumpNames('James', 'Jonty', 'Jeremy');

// will dump
// array (size=3)
//     0 => string 'James' (length=5)
//     1 => string 'Jonty' (length=5)
//     2 => string 'Jeremy' (length=6)

When you send multiple parameters into the function, PHP will combine them into one array and store in the given variable prefixed with …

In PHP 7.4, the spread operator can be used in Array Expressions. This process is kind of the opposite of the previous one.

$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];

Here, we give an array, and PHP will extract the elements of the array in the given place.

The RFC encourages using the spread operator over array_merge for better performances and to support Traversable.

Unlike argument expansion, we can use the same expansion multiple times in the same array expression (which is logical right?).


$sisterNumbers = [1,2,3];
$brotherNumber = [9,11,13];

$dadNumbers = [...$sisterNumbers, ...$brotherNumber, 42, 34]; // 1,2,3,9,11,13,42,34
$motherNumbers [...$sisterNumbers, ...$sisterNumbers]; // 1,2,3,1,2,3

  • This work for both array() and [] syntax.
  • This will only work on arrays that have numerical keys.
  • You can unpack an array returned by a function immediately. Ex: $x = [1,3, …someFunction()]
  • You cannot unpack an array by reference.

5. Numeric Literal Separator

What a cool idea! You can now, since PHP 7.4, add underscores in numeric variables.

// previously
$price = 340523422.88; // hard to read

// now
$price = 340_523_422.88; // easy to read

PHP will ignore the _s and compile the PHP file. The only reason to add this feature is to allow developers to have more clean & comprehensible code.

The Numeric Literal Separator can be used in any numeric type (integers, float, decimal, hexadecimal, and binary).

2.554_083e-4; // float
0x46FC_FA5D;   // hexadecimal
0b0111_1101;   // binary

In this post, I mentioned the top 5 features of PHP 7.4. Hope this post will be helpful to you.

Thanks for reading !

#php #web-development

Learn The top 5 Features of PHP 7.4 With Examples
2 Likes22.25 GEEK