New Features of PHP 7.4

Introduction: PHP is a popular general-purpose scripting language. It is used for web development. It was created by Rasmus Lerdorf in 1994, the PHP reference implementation is now produced by the PHP Group.

PHP 7.4 Update 2019: New features from time to time are very essential and important for any language to grow. PHP is one of the popular languages for many years and one main reason for that is they keep on updating it and adding new features to it from time to time. The performance of PHP from its initial release is far better nowadays. Also, PHP is one of the top 10 most popular programming languages.

New Features: Some new features of PHP 7.4 are Listed Below:

1. Spread operator in Array: PHP 7.4 will give the power to use spread operators in arrays that are faster compared to array_merge. A spread operator is considered to be a language structure and array_merge is a function. Also, compile-time has been optimized.

Example: These are the illustration of the new features added and how may they work.



filter_none

edit
close

play_arrow

link
brightness_4
code

$prime = ['2', '5'];
$all = ['1', '3', ...$prime, '7'];

chevron_right


Output:

1, 3, 2, 5, 7

2. Weak References: In PHP 7.4, the WeakReference class allows us to save a link to an object. It is not like the WeakRef class of the Weakref extension. Due to this feature, we can easily implement cache-like structures.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
class Cache {
      
    // var WeakReference[]
    private $objects = [];
       
    // $id is an identifier to store
    // the object, int|string
      
    // Return the stored object,
    // or null if that object is
    // not in the cache
    public function getObject($id) {
        $reference = $this->objects[$id] ?? null;
           
        if($reference === null){
            return null;
        }
           
        return $reference->get();
    }
       
    // The $id is the identifier for
    // the stored object, int|string
    // $object is used to store the object
    public function setObject($id, $object) {
        $this->objects[$id] = 
            WeakReference::create($object);
    }
}
?>

chevron_right


The above code is an example of weak reference. A weak reference is similar to a normal reference, except that it doesn’t prevent the garbage collector from collecting the object.
WeakReference should not be confused with WeakRef which is a PHP extension, and not a native part of PHP.

3. Preloading: This feature we can upload files, libraries in OPcache. These features enable us to preload the files into memory.

Example: It is just a dummy implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

$files = /* An array of files 
    that you want to preload */;
  
foreach ($files as $file) {
    opcache_compile_file($file);
}

chevron_right


Every PHP file that you want to be preloaded should be passed to opcache_compile_file() or be required once, from within the preload script.

4. Arrow function: It removes the complexity which was there before, as using anonymous functions increases complexity in the PHP. Now, these features allow us to make our code more concise and clean it up. This is just to remove complexities and make code simpler.

filter_none

edit
close

play_arrow

link
brightness_4
code

// A collection of Post objects
$posts = [/* … */];
  
$ids = array_map(function ($post) {
    return $post->id;
}, $posts);

chevron_right


Before the update we have to write the code as mentioned above.



filter_none

edit
close

play_arrow

link
brightness_4
code

// A collection of Post objects
$posts = [/* … */];
  
$ids = array_map(fn($post) => $post->id, $posts);

chevron_right


  • They start with keyword fn
  • They only have one expression, which is return statement
  • No return keyword allowed

5. Throwing exceptions from __toString() function: Previously, the function used to convert an object to string were present in the standard library, and also many of them did not process exceptions correctly.

Syntax:

public Exception::__toString( void ) : string

Return Value: It is a string representation of exception.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
try {
    throw new Exception("error");
} catch(Exception $e) {
    echo $e;
}
?>

chevron_right


6. Coalescing assign operator: This is very helpful when we have to use the ternary operator together with isset() function. This enables you to return the first operand if it exists, If not, it will return the second operand. Null coalesce equal operator was introduced in PHP 7 to simplify isset() check with the ternary operator.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Before the 7.4 release
$data['username'] = $data['username'] ?? 'guest';
  
// After 7.4 new feature
$data['username'] ??= 'guest';

chevron_right


7. Numeric literal separator: Numeric literals can contain underscore between digits.

filter_none

edit
close

play_arrow

link
brightness_4
code

6.674_083e-11; // float
299_792_458;   // decimal
0xCAFE_F00D;   // hexadecimal
0b0101_1111;   // binary

chevron_right


Filter: The FILTER_VALIDATE_FLOAT filter supports the min_range and max_range options, with the same semantics as FILTER_VALIDATE_INT.

FFI: FFI is a new extension, and it is a simple way to call native functions, access native variables, and create/access data structures defined in C libraries.

GD: Added the IMG_FILTER_SCATTER image filter used to apply a scatter filter to images.

Hash: Added crc32c hash using Castagnoli’s polynomial. This CRC32 variant is used by storage systems, such as iSCSI, SCTP, Btrfs and ext4.

PDO: The username and password can be specified as part of the PDO DSN for the mysql, mssql, sybase, dblib, firebird and oci drivers. Before php 7.4 release this feature was only supported by the pgsql driver.

Reference: https://www.php.net/manual/en/migration74.new-features.php




My Personal Notes arrow_drop_up

Check this out nerdboinet

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.