Karachi, Pakistan hello@owncodes.com

Office Address

Social List

What New in PHP 7.4

blog image

What New in PHP 7.4

Since 2016, PHP7 has been releasing annual updates without fail. Each year they deliver on new features, additions, and the possibility to write cleaner code that makes the language more reliable and user-friendly for those who run it on their websites.

Let’s dig in and take a closer look at some of the changes that were made with the addition of PHP 7.4. For a full list check out their change-log here.

Preloading

Let’s talk about code. When using a framework or libraries, its files have to be loaded and linked on every request. Preloading is when you can load frameworks and libraries into the OPCache. It allows for the server to load the PHP files and store them in memory during startup and have them available for any future requests. Talk about getting things going quick!

Preloading is run by a specific php.ini directive: opache.preload.This has the PHP script compiler and executes when the server starts-up. It can also be used to preload more files and choose to either include or compile them.

This is awesome, however, if the source of the preloaded files is ever changed, the server must be restarted. The preloaded files also remain cached in OPCache memory forever.

However, these preloaded files will continue to be available for any future requests in case you ever need to use them again.

Spread Operator in Array Expressions

Back when PHP 5.6 was released, PHP began supporting argument unpacking (spread operator) but now, with 7.4, we are able to use this feature with an array expression. Argument unpacking is a syntax for unpacking arrays and Traversables into argument lists. And, in order to do so, it only needs to be prepended by … (3 dots.) That’s it.

Let’s look at this example:

$animals = ['dog', 'cat'];
$animalkingdom = ['lion', 'elephant', ...$animals,'giraffe'];
// [‘lion’, ‘elephant’, ‘dog’, ‘cat’, ‘giraffe’];

We can now expand an array from anywhere we want in another array, by simply using the Spread Operator syntax.

Here is a longer example:

$num1 = [1, 2, 3];
$num2 = [...$num1]; // [1, 2, 3]
$num3 = [0, ...$num1]; // [0, 1, 2, 3]
$num4 = array(...$num1, ...$num2, 111); // [1, 2, 3, 1, 2, 3, 111]
$num5 = [...$num1, ...$num1]; // [1, 2, 3, 1, 2, 3]

Not only that, but you can also use it in a function. Check out this example:

functiongetNum(){
return['a', 'b'];
}
$num6 = [...getNum(), 'c']; // ['a', 'b', 'c']
$num7 = [...newNumIterator(['a', 'b', 'c'])]; // ['a', 'b', 'c']
functionarrGen(){
for($i = 11; $i

Leave A Comment