PHP 7.2 and Allow Abstract Function Override


PHP 7.2 has been released on 30th of November 2017. The most important features have been listed out and briefly described, however there is much more to be explored.

Without further ado, let’s dive into Allow Abstract Function Override together.


Try it yourself

Clone blogging-phplatest repository

Run docker container, based on the php 7.2.0 CLI Stretch Container


As presented below,  Mammal::run method has broaden the $speed parameter type from a stdClass to no-type, also known as Contravariant. If you tried to do it other way around (Covariant), you would get Fatal error: Declaration of Mammal::run(stdClass $speed) must be compatible with Animal::run($speed), because PHP doesn’t yet support full-featured type variance.

Additionally, if you tried to run this piece of code in PHP 7.1 or earlier, you would encounter: Fatal error: Can’t inherit abstract function Animal::run() (previously declared abstract in Mammal) 

Feel free to verify it yourself by running it in the PHP 7.1 CLI Jessie Container

How did we do it until now

Without type variance, each abstract method in child classes must conform to the method signature of its parent class.


At this point it doesn’t look that beneficial, however, according to the author of this RFC, it will gain more uses when PHP will support a full-featured type variance.

If you enjoyed this post, then make sure you subscribe to my Newsletter