LogoLoading Please Wait...

What’s new in PHP 7.4?

By divine_admin_infosys

PHP 7.4, the following PHP 7 minor release, has been released on November 28th, 2019. So it’s the ideal opportunity for us to plunge into the absolute most energizing augmentations and new highlights that will have made PHP quicker and progressively reliable.

Features of PHP 7.4:

  1. Support For Arrow Function :
    • Since mysterious capacities, or terminations, are basically applied in JS, they appear to be verbose in PHP. Their execution and support systems are likewise progressively intricate.
    • The presentation of arrow functions’ help will empower PHP designers to significantly tidy up their code and make the linguistic structure progressively succinct. Therefore, you will get a more significant level of code comprehensibility and effortlessness.
  • Code in Previous PHP Version:
function test($a){

               return ($a * $a * $a);

}

               $c = [1, 2, 3, 4, 5];

               $d = array_map('cube', $c);

       print_r($d);

 

  • Code in PHP 7.4 Version:
$c = [1, 2, 3, 4, 5];

$d = array_map(fn($b) => $b * $b * $b, $c);

print_r($d);

  • On account of the capacity to make perfect, shorter code, the web improvement procedure will speed up, enabling you to spare time.
  1. Typed Property’s Support :
    • Typed properties have been absent in PHP since long. They are presently accessible in PHP 7.4. By utilizing them, you can simply declare type hints to the class variables and properties. Previously, it was unrealistic and you needed to make getter and setter techniques to implement type contracts.
    • Because of declaration types (barring void and callable), you can utilize nullable types, int, float, array, string, object, iterable, self, bool, and parent.
    • If a web developer tries to assign an irrelevant value from the type, for instance, declaring $name as string, he or she will get a TypeError message.
  • Code In Previous PHP Version :
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;

    }

}

 

  • Code In  PHP 7.4 Version :
class User {

    public int $id;

    public string $name;

    public function __construct(int $id, string $name) {

        $this->id = $id;

        $this->name = $name;

    }

}

  1. Preloading :
    • The fundamental reason for this cool new element is to build PHP 7.4 execution. Basically, preloading is the way toward stacking files, systems, and libraries in OPcache and is unquestionably an extraordinary expansion to the new release. For instance, if you use a framework, its files must be downloaded and recompiled for each request.
    • While configuring OPcache, just because these code files participate in the request handling and afterward they are checked for changes each time. Preloading empowers the server to load the predefined code documents into shared memory. Note that they will be constantly accessible for every single subsequent request without extra checks for file changes.
    • It is likewise essential to make reference to that during preloading, PHP additionally wipes out unnecessary incorporates and resolves class conditions and connections with qualities, interfaces, and that’s just the beginning.
  1. Covariant returns & Contravariant Parameters :
    • Right now, PHP has, for the most part, invariant parameter types and invariant return types which exhibit a few limitations. With the presentation of covariant (types are requested from increasingly explicit to progressively conventional) returns and contravariant (types are requested from increasingly nonexclusive to increasingly explicit) parameters, PHP designers will have the option to change the parameter’s sort to one of its supertypes. The returned type, thusly, can be effectively supplanted by its subtype.
    • Specifically, a parameter type can be filled in for one of its supertypes and a return type can substitute a subtype, and you can utilize covariant type in a most recent PHP form.
  • Code In PHP 7.4 Version :
class A {}

        class B extends A {}



        class Producer {

            public function method(): A {}

        }

        class ChildProducer extends Producer {

            public function method(): B {}

        }

  1. Weak Reference :
    • In PHP 7.4, the WeakReference class permits web designers to save a link to an object that doesn’t prevent its destruction. Try not to mistake it for the WeakRef class of the Weakref extension. Because of this component, they can all the more effectively execute cache-like structures.
  • Code In PHP Version 7.4 :
<?php

   $obj = new stdClass;

   $weakref=WeakReference::create($obj);

   var_dump($weakref>get());

   unset($obj);

   var_dump($weakref->get());

?>
  • You Can’t Serialize Weak Reference
  1. Coalescing Assign(??=) Operator :
    • A Coalesce Operator is another new element accessible in PHP 7.4. It’s extremely useful when you have to apply a ternary operator together with isset(). This will empower you to return the first operand if it exists and is not NULL . If not, it will simply return the second operand.
  • Code In Previous PHP Version:
$someArray['key'] = $someArray['key'] ?? 'someValue';

  • Code In PHP 7.4 Version:
$someArray['key'] ??= 'someValue';

  1. A Spread Operator in array expression:
    • PHP 7.4 will provide specialists to utilize spread operators in an array that are quicker compared with array_merge. There are two key purposes behind that. Initial, a spread operator is viewed as a language structure and array_merge is a function. The subsequent explanation is that now your compile time can be streamlined for constant arrays. As a result, you will have expanded the PHP 7.4 execution.
  • Code in PHP 7.4 Version :
$a = ['3', '4'];

$b = [1, 2, ...$a, '5'];

var_dump($b);

  • Likewise, it will be conceivable to extend a similar array on numerous occasions. Moreover, since ordinary components can be included previously or after the spread operator, PHP engineers will be able to use its syntax in the array.
  1. A new custom object serialization mechanism:
  • In the new version of PHP, two new techniques become accessible: __serialize and __unserialize. Joining the adaptability of the Serializable interface with the methodology of executing __sleep/__ wakeup techniques, this serialization component will permit PHP engineers to evade customization issues related to the current methods. Find out more information about this PHP feature.
  1. Reflection for References :
  • Libraries, for example, Symfony/var-dumper, intensely depend on ReflectionAPI to precisely show variables. Beforehand, there was no appropriate help for reference reflection, which constrained these libraries to depend on hacks to identify references. PHP 7.4 includes the ReflectionReference class which takes care of this issue.
  1. Support For throwing exceptions from _toString():
  • Previously there was no possibility to throw exceptions from the __toString method. The purpose behind that is the transformation of items to strings is performed in numerous functions of the standard library, and not every one of them is prepared to “process” special cases effectively. As a component of this RFC, a thorough audit of string transformations in the codebase was carried out and this restriction was evacuated.

Deprecation in PHP 7.4:

  • New features consistently accompany the deprecation of old features or parts. PHP 7.4 will release with some referred deprecations as well. Let’s see what they are:
  1. Short Open Tags :
  • Short open tags ?> are currently deprecated and will be totally removed in PHP 8.0
  1. Left-Associative Ternary Operator:
    • The ternary operator in PHP is left-associative rather than right-associative like different languages. This conduct isn’t so valuable in PHP. This RFC proposes to deprecate and expel left-associativity for the ternary operator and requires explicit use of parentheses.
  • For Example :
1 ? 2 : 3 ? 4 : 5; // deprecated

(1 ? 2 : 3) ? 4 : 5; // ok

1 ? 2 : (3 ? 4 : 5); // ok

  1. Curly Braces Syntax:
    • In PHP, you can use curly braces and square brackets to access array elements. But in PHP 7.4, you cannot use curly braces as it will throw parse error.
  • For Example 
$array[] = 3;

echo $array[2]; // prints 3

$array{} = 3; // Parse error: syntax error, unexpected '}'

Conclusion:

  • There are a lot of new PHP highlights that decrease memory utilization and significantly increment PHP 7.4 execution. You will pick up the capacity to keep away from some past limitations of this programming language, compose cleaner code, and make web arrangements quicker.
Divine Infosys