What is new in PHP 7.2?

Español English

In this post we’re going to check 5 new features of PHP 7.2

1. New object type

Before PHP 7.2 the object keyword was used to convert one data type to another (boxing and unboxing), for example, an array to an object of the sdtClass class and/or vice versa, as of PHP 7.2 the object data type can be used as parameter type or as function return type.

<?php

function test(object $obj): object
{
    echo 'Param is type of: ', gettype($obj), nl2br("\n");
    return new SplQueue();
}

$result = test(new StdClass());
echo 'Return is type of: ', gettype($result), nl2br("\n");

// Print
// Param is type of: object
// Return is type of: object

2. Extension loading by name

Now PHP configuration file is more portable between differents platform (Windows, MacOS, GNU/Linux) due shared extensions no longer require their file extension (.so for Unix or .dll for Windows) to be specified. This is enabled in the php.ini file, as well as in the dl() function.

3. Abstract method overriding

Abstract methods can now be overridden when an abstract class extends another abstract class.

<?php

abstract class A
{
    abstract function test(string $s);
}

abstract class B extends A
{
    abstract function test($s) : int;
}

Note that the following overriding style is not allowed

<?php
abstract class A
{
    abstract function test($s);
}

abstract class B extends A
{
    abstract function test(string $s) : int;
}

The above example raise the following error:

Fatal error: Declaration of B::test(string $s): int must be compatible with A::test($s)

4. Sodium is now a core extension

Sodium is a modern and easy to use library that allows encryption, decryption, signatures, password hashing and mor… now the extension is part of the PHP core. For a complete function reference, see the Sodium chapter.

5. Parameter type widening

Parameter types from overridden methods and from interface implementations may now be omitted. This is still in compliance with LSP, since parameters types are contravariant.

<?php

interface A
{
    public function test(array $input);
}

class B implements A
{
    public function test($input) {}
}

To see all the changes introduced by PHP-7.2, see Migrating from PHP 7.1.x to PHP 7.2.x


YouTube video

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.