PHP 7.2 was released in November 2017, but in practice many projects are only migrating to this version now. If you are still on 7.0 or 7.1 – this post is for you. I go through the most important changes that have a real impact on everyday code.
1. Object type hint in parameters and return values
PHP 7.2 is the first version to allow object as a type hint. It sounds simple, but in practice it greatly cleans up interfaces that accept any object:
<?php
// Before PHP 7.2 - no type hint, you have to check manually
function logObject($obj): void {
if (!is_object($obj)) {
throw new \InvalidArgumentException('Expected object');
}
}
// PHP 7.2 - the "object" type hint does it for you
function logObject(object $obj): void {
echo get_class($obj);
}
Particularly useful when writing generic logging, serialising, or data-mapping helpers for external APIs.
2. Parameter type widening (contravariance)
In PHP 7.2 you can widen a parameter type hint in a child class – replacing a more specific type with a more general one. Before 7.2 PHP threw an error.
<?php
class Collection {}
class SpecialCollection extends Collection {}
class ParentHandler {
public function handle(SpecialCollection $c): void {}
}
// PHP 7.2: you can widen the type to Collection or object
class ChildHandler extends ParentHandler {
public function handle(Collection $c): void {}
}
In Magento 2 keep this in mind when overriding methods through plugins or preferences.
3. Libsodium in core – end of mcrypt
The Sodium library is now officially in the PHP core. mcrypt was removed (deprecated since 7.1). If you have old encryption code using mcrypt_encrypt() – it is high time to migrate:
<?php
// OLD - mcrypt removed in PHP 7.2!
// $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
// NEW - sodium, secure and fast
$key = sodium_crypto_secretbox_keygen();
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$encrypted = sodium_crypto_secretbox('Secret message', $nonce, $key);
$decrypted = sodium_crypto_secretbox_open($encrypted, $nonce, $key);
echo $decrypted; // Secret message
Summary
PHP 7.2 is a solid, evolutionary release. It closes several long-standing pain points (sodium instead of mcrypt, the object type hint). If you are planning a future migration to PHP 8.x, upgrading to 7.2 is a good first step.
