Pilih Laman

sumber: https://www.niagahoster.co.id/blog/php-7-4/

1. Preloading

Programming using a framework or library requires you to upload and link individual files in each request. Thanks to the preloading feature, you can upload frameworks and libraries into OPCache — which allows “storage” of PHP files on the server. The files will then be compiled and run automatically for every request that requires them. Practical, right? To determine what files you want to be preloaded and run automatically, you need to look at one of the commands in the php.ini file, namely opcache.preload. However, keep in mind that changing preloaded files will require you to restart the server.

2. Spread Operators in Array Expressions

The argument unpacking or spread operator, the syntax used to describe arrays and traversables into argument lists, has been around since PHP 5.6. However, version 7.4 allows you to use it with array expressions. You just need to add three dots in front of the spread operator to use it. To make it clearer, consider the example below:

$hewan = [‘anjing’, ‘kucing’]; $kerajaanhewan = [‘singa’, ‘gajah’, …$hewan, ‘jerapah’]; // [‘singa’, ‘gajah’, ‘anjing’, ‘kucing’, ‘jerapah’];
In this example, $animal can be translated into another array by adding three dots in front of it. In addition, you can also use the spread operator in a function, as in the following example:

function getNum() {   return [‘a’, ‘b’]; } $num6 = […getNum(), ‘c’]; // [‘a’, ‘b’, ‘c’] $num7 = […new NumIterator([‘a’, ‘b’, ‘c’])]; // [‘a’, ‘b’, ‘c’] function arrGen() {     for($i = 11; $i < 15; $i++) {         yield $i;     } } $num8 = […arrGen()]; // [11, 12, 13, 14]
Plus, you can directly describe arrays and generators returned by a function in another array. For example, as shown below:

function getHewan(){  return [‘anjing’, ‘kucing’, ‘gajah’]; } $num1 = […getHewan(), ‘singa’, ‘harimau’, ‘jerapah’];
Here is the result of the function when compiled with PHP 7.4:

array(6) {
 [0]=>
 string(3) "anjing"
 [1]=>
 string(3) "kucing"
 [2]=>
 string(8) "gajah"
 [3]=>
 string(4) "singa"
 [4]=>
 string(5) "harimau"
 [5]=>
 string(7) "jerapah"
} 

3.Generator Function
The generator function functions like a normal function. However, it can store as much value as possible. Below is an example:
  • function generator() { for ($i = 3; $i <= 5; $i++) { yield $i; } } $num1 = [0, 1, 2, …generator()];

    4. WeakReference The WeakReference class allows you to maintain a reference to an object. This feature is useful in implementing cache-like structures. Examples are as follows:
    WeakReference { /* Methods */ public __construct ( void ) public static create ( object $referent ) : WeakReference public get ( void ) : ?object }

    5. Contravariant Parameter and Covariant Return
    So far, PHP uses invariant parameters and returns. That is, if the parameter or return of a method is X, the subtype of the parameter or return must also be X. However, PHP 7.4 provides covariant (from specific to general) and contravariant (from general to specific) parameters and returns. Here is an example of using both.

 

interface Factory {
 function make(): object;
}
class UserFactory implements Factory {
 function make(): User;
}

Contravariant parameter:

  • interface Concatable { function concat(Iterator $input);  } class Collection implements Concatable { // accepts all iterables, not just Iterator function concat(iterable $input) {/* . . . */} }

    6. Null Coalescing Assignment Operator coalesce operator ?? useful when you use the ternary operator with isset(). This operator will return the first operand. If the first operand is null, the second operand is returned. To make it clearer, consider the following example:

$username = $_GET['user'] ?? ‘nobody';
  • Although these lines of code look simple, their implementation gets complicated when you enter long variables, as in the example below:
$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';

  • The good news is that in PHP 7.4 you can shorten the code above with a null coalescing assignment operator represented by the ??= symbol. With this operator, the above code can be shortened to this:
$this->request->data['comments']['user_id'] ??= ‘value’;

7. Typed Properties 2.0

An argument type declaration or type hint allows you to type the variable you want to pass to a function or class method. This feature has been around since PHP 5, but was improved in PHP 7.4 with a first class property type declaration. This feature supports all variable types, including bool, int, float, string, array, object, iterable, self, parent, and nullable types. However, void and callable are not supported by typed properties because they have less clear semantics. Using typed properties can reduce the time you need to write code. Consider the comparison of writing code for classes in the example below.

class User {
    /** @var int $id */
    private $id;
    /** @var string $name */
    private $name;
    public function __construct(int $id, string $name) {
        $this->id = $id;
        $this->name = $name;
    }
    public function getId(): int {
        return $this->id;
    }
    public function setId(int $id): void {
        $this->id = $id;
    }
    public function getName(): string {
        return $this->name;
    }
    public function setName(string $name): void {
        $this->name = $name;
    }
} 

The code above is written in PHP 7.3. Long isn't it? Now compare it with the below code written in PHP 7.4.
class User {
    public int $id;
    public string $name;
    public function __construct(int $id, string $name) {
        $this->id = $id;
        $this->name = $name;
    }
} 

  • With typed properties, you can also specify property values. However, you need to remember that the property value must match the property type. In addition, a null value can only be owned by a null property. Otherwise, you will encounter a fatal error. Take a look at the following example:
class User {
public int $id;
public string $name;
}

$user = new User;
$user->id = 10;
$user->name = [];

  • In this example, the specified property type is a string. In fact, the property value is an array. Therefore, an error like the one below will appear:
Fatal error: Uncaught TypeError: Typed property User::$name must be string, array used in /app/types.php:9

8. Arrow Functions 2.0

Anonymous functions in PHP generally consist of long lines of code, even for simple operations. To solve this problem, an arrow function was created. To see how this feature works, let’s consider the following examples. Below is the code written with PHP 7.3:

function array_values_from_keys($arr, $keys) {
    return array_map(function ($x) use ($arr) { return $arr[$x]; }, $keys);
}

Dengan PHP 7.4, kodenya akan terlihat seperti demikian:

function array_values_from_keys($arr, $keys) {
    return array_map(fn($x) => $arr[$x], $keys);
} 

  • With arrow functions, the code can be shortened even more:
fn(parameter_list) => expr

  • Here we show another example, where $fn1 is written in PHP 7.3 and $fn2 is written in PHP 7.4.
$y = 1;
$fn1 = fn($x) => $x + $y;
$fn2 = function ($x) use ($y) 
{
    return $x + $y;
};

Dengan arrow function, kode di atas menjadi:

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

  • Arrow functions support a variety of function types, including variadics, default values, parameter types and return types, as well as by-reference passing and returning. Here are the arrow functions for these functions:
fn(array $x) => $x;
fn(): int => $x;
fn($x = 42) => $x;
fn(&$x) => $x;
fn&($x) => $x;
fn($x, ...$rest) => $rest;

  • In addition, the arrow function is a function that is least prioritized in an operation. If you write fn($x) => $x + $y, the operation takes precedence over $x + $y, not fn($x) => $x.