PHP 7.2 : What got introduced?
21, December 2019

Parameter type widening

PHP till version 7.2 doesn't support parameter type variance. So we can't change type definition when overriding a method.

<?php
// PHP 7.1
interface A {
    public function call(string $name);
}

interface B extends A {
    // we can't remove parameter type here
    // because, A has defined parameter type as string
    public function call($name);
}
// Declaration of B::call($name) must be compatible with A::call(string $name)

But, PHP 7.2 allows us to remove type definition and accept any type of value when overriding a method.

// PHP 7.2
interface A {
    public function call(string $name);
}

interface B extends A {
    // this is allowed
    public function call($name);
}
// However, we can't change type to other type, we just can omit them


Abstract method overriding

Abstract methods now can be overridden in a abstract class. Both Parent-Class and Child-class must be Abstract.

abstract class Human {
    abstract function read(string $text);
}

abstract class Student extends Human {
    // We can override this method as this is abstract class
    abstract function read($text): bool;
}


New object type

We now can define object as parameter type and return type. This can be helpful if we want to accept or return different class instance in our method.

class Dog {
}

class Cat {
}

function pat(object $animal){
   // This function will accept both Dog & Cat instance
}

function callAny(): object {
   // This function can return any of Cat or Dog
}


Allow a trailing comma for grouped namespaces

Trailing comma is supported to the all list like places

  • Grouped namespaces
  • Interface implementation
  • Trait implementation
  • Inheriting variables from parent scope to anonymous function


Argon2 In password hash

PHP 7.2 allow us to hash password using Argon2.

$password = password_hash('strong password', PASSWORD_ARGON2I);


New Sodium extension

The modern Sodium cryptography library has now become a core extension in PHP. Libsodium is a cross-platform and cross-languages library for encryption, decryption, signatures, password hashing and more. Previously, Sodium was available as PECL extenstion.


Deprecation

  • __autoload : is now deprecated. To implement autloading functionality, everyone should adopt spl_sutoload_register()
  • each() : is now deprecated. To iterate over arrays, please use foreach, it is much faster.

Write comment about this article: