Home » Releases » PHP 7.2 »

PHP 7.2 Code Comparisons

Explore PHP 7.2

Object Type Declaration

PHP 7.2 introduces object as a valid generic type hint. It accepts any object instance, excluding scalars and non-object values, providing better type safety for APIs working with arbitrary objects.
Before PHP 7.2
class Processor {
    public function process($data)
    {
        if (!is_object($data)) {
            throw new TypeError(
                'Expected object'
            );
        }
        return $data;
    }
}
PHP 7.2 or Later
class Processor {
    public function process(object $data): object
    {
        return $data;
    }
}

Argon2 Password Hashing

PHP 7.2 adds native support for the modern Argon2 hashing algorithm (PASSWORD_ARGON2I and PASSWORD_ARGON2ID), offering a secure, memory-hard alternative to Bcrypt for password storage.
Before PHP 7.2
$hash = password_hash(
    $password,
    PASSWORD_BCRYPT,
    ['cost' => 12]
);
PHP 7.2 or Later
$hash = password_hash(
    $password,
    PASSWORD_ARGON2ID,
    [
        'memory_cost' => 1024,
        'time_cost' => 2,
        'threads' => 2,
    ]
);

Sodium Cryptography Extension

PHP 7.2 integrates the Sodium cryptography library into core. It provides secure defaults for authenticated encryption, public-key cryptography, hashing, and password derivation without requiring third-party PECL packages.
PHP 7.2 or Later
$key = random_bytes(
    SODIUM_CRYPTO_SECRETBOX_KEYBYTES
);
$nonce = random_bytes(
    SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
);
$cipher = sodium_crypto_secretbox(
    'Secret message',
    $nonce,
    $key
);

Abstract Method Overriding in Traits

PHP 7.2 allows traits to specify abstract methods. Classes using the trait are required to implement these abstract methods, enabling better architectural constraints and documentation within trait definitions.
Before PHP 7.2
trait LoggerTrait
{
    public function log(string $msg): void
    {
        // Base logging
    }
}
PHP 7.2 or Later
trait LoggerTrait {
    abstract public function getChannel(): string;

    public function log(string $msg): void
    {
        $channel = $this->getChannel();
        // ...
    }
}