PHP 7.2 and Allow Abstract Function Override

|2 min read|
Teklog
Teklog

Introduction

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.

Assumptions

Try it yourself

Clone blogging-phplatest repository

git clone https://github.com/tekmi/blogging-phplatest
cd blogging-phplatest

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

docker run -it --rm \
-v "$PWD":/usr/src/php-7.2 \
-w /usr/src/php-7.2 \
php:7.2.0-cli-stretch \
php php-7.2/abstract_function_override/index.php

Explanation

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.

abstract class Animal
{
  abstract public function run(\stdClass $speed);
}

abstract class Mammal extends Animal
{
  abstract public function run($speed);
}

class Lion extends Mammal
{
  public function run($speed)
  {
    return "Runs $speed km/h";
  }
}

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

docker run -it --rm \
-v "$PWD":/usr/src/php-7.2 \
-w /usr/src/php-7.2 \
php:7.1.12-cli-jessie \
php php-7.2/abstract_function_override/index.php

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.

Summary

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.