03Feb
PHP 7.4
PHP 7.4

PHP 7.4, the latest version of the PHP 7 series; it was introduced on the 28th of November 2019. There is a bunch of exciting new features added. There are two primary focuses on this update: improved performances and bug fixes. The most important thing for us, as PHP developers, is to check out the latest features in PHP 7.4. There are cool 😎 ones – believe me.

New Features Pack

  1. Arrow Functions (fn() syntax)
  2. Typed Properties
  3. Null coalescing assignment operator
  4. Spread Operator in Array Expression
  5. Numeric Literal Separator
  6. Preloading

1. Arrow Functions

arrow
arrow

This is a feature that got accepted in April 2019 and loved by the PHP community. It only does one thing, and that is making the function syntax less verbose. Which type of developers doesn’t like concise programming?

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.

$names = array_map(function($user) {
    return $user -> name
}, $users);

But, now…

$names = array_map(fn($user) => $user -> name, $users);

It’s just one line.

fn($user) => $user -> name;
//                 ^^^^^^^^^^^^^^
//                 This actually returns the value even there isn't a return statement

The form of the arrow functions is:

fn(params) => expression

The expression is always a return statement even the return keyword isn’t there.

When you use a variable defined in the parent scope in an arrow function, the variable will be implicitly captured by-value

Nested arrow functions are also allowed.

$z = 1;
$fn = fn($x) => fn($y) => $x * $y + $z;

$z in the parent scope, goes down the hierarchy to the most inner function.

Other facts:

$fn = fn(int $x) : int => $x + 2;

$fn(4); // 6
$fn('4'); // 6 (due to implicit casting)
$fn([4,5]); // error

2. Typed Properties (version 2.0)

pan
pan

Type hinting for 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.

3. Null Coalescing Assignment Operator

Null Coalescing operator in PHP 7 made a huge difference in PHP development because we could write the following code.

$data['name'] = isset($data['name']) ? $data['name'] : 'Guest';

simply as this:

$data['name'] = $data['name'] ?? 'Guest';

Now, things have become more interesting. It’s now just:

$data['name'] ??= 'Guest';

All of the above codes do the same thing. Check if the $data['name'] is set. If yes, get it. If not, get “Guest” and assigns to $data['name']. As I mentioned, PHP 7.4 update makes the syntax less verbose.

This can be useful when you have some long variables:

$data['top_group']['people'][1]['name'] = $data['top_group']['people'][1]['name'] ?? 'Guest';
                                        // ^^^ Repitition

// can be written as
$data['top_group']['people'][1]['name'] ??= 'Guest';

Simple, if the value of the left-hand side is null (or not set), the value of the right-hand side will be assigned to the left.

4. Spread Operator in Array Expression

Since PHP 5.6, the splat operator (... or 3 dots) has been used to unpack arrays (or any other Traversables) into arguments.

We write:

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

Facts.

  • 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

6. Preloading

Devised by Dmitry Stogov, Preloading was first controversial, and later much loved by the PHP community. However, again, it made some bad impressions due to the bugs it had in the first version. However, the latest PHP 7.4.2 comes with bug fixes.

So, what’s preloading? Simply it’s PRELOADING. Dmitry says,

On server startup – before any application code is run – we may load a certain set of PHP files into memory – and make their contents “permanently available” to all subsequent requests that will be served by that server. All the functions and classes defined in these files will be available to requests out of the box, exactly like internal entities.

Here’s the process.

  • First, we write a PHP script and add it to opcache.preload directive in php.ini.
  • This PHP file will be executed when you (re)start the server.
  • It can be used to preload additional PHP files.
  • All preloading files will be saved in the memory.
  • Server will execute those files from memory.
  • Changes to those files are ignored by the server as it runs from the already loaded version of the script.
  • If needed to update, you have to restart the server.

Brent from Stitcher.io has written a complete guide on implementing preloading. His benchmark (However, based on only a specific type of data) shows that preloading can improve performances up to 25%.

Conclusion

In this article, we discussed the top 6 features of PHP 7.4. There are several other features in this update. The latest stable version is PHP 7.4.2 (As of 01/24/2020). If you are using PHP 7.4, it’s better to upgrade to PHP 7.4.2 for the sake of performance.

If you are using an old version of PHP (7.x), you may consider upgrading. However, there are factors you should consider. First, if you are working with a team, you have to discuss it together if there’s a need for upgrading. True, PHP 7.4 is more performant than the previous version, but, “how much better” isn’t yet properly assessed.

If you have upgraded to PHP 7.4, you can take advantage of the new features mentioned in this article. However, make sure that everyone in your team (PHP devs) is comfortable with these concepts. See why Dan Abramov said Goodbye to Clean Code to learn why that’s important.

Finally, if you are still a PHP 5.x user, you should consider upgrading to PHP 7 soon, says Rasmus, the founder of PHP.

Thank you!

Nodejs Lesson 15: Internals of Nodejs: LibUV

Hello everyone, today we are going to talk about the internals of Nodejs. This article will guide how node js works and how it can handle async tasks. What will happen if ten requests come at once? Will it handle one request and discard the other 9? or will it create a queue and serve each one by one. We will answer all these questions in this and coming lesson. Let’s start.

Full Node.js Course

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Please welcome, our first series of article about Node.js!

2 Replies to “Top 6 Features of PHP 7.4 – Explained with Examples”

  1. Need to add:
    1. Covariant returns & contravariant parameters
    2. Weak References
    3. A new custom object serialization mechanism
    4. Reflection for references
    5. Support for throwing exceptions from __toString()

  2. PHP 7.4 has some limitations as well. I wouldn’t call it a stable release. For example some CMS versions are not supported, like Magento 1. There are some encryption apps that are not supported either. I haven’t upgrade to PHP 7.4 because of this. see here: https://www.cloudways.com/blog/php-7-4/

Leave a Reply