Skip to content

Instantly share code, notes, and snippets.

@kelunik
Last active November 14, 2016 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kelunik/7eb89b807dadda3edd05b4c48a23be06 to your computer and use it in GitHub Desktop.
Save kelunik/7eb89b807dadda3edd05b4c48a23be06 to your computer and use it in GitHub Desktop.
PHP Parameter Variance

Parameter No Type Variance

Introduction

PHP doesn't currently allow variance for parameters as checking these for compatibility isn't possible on compile time. This limitation is caused by autoloading and doesn't allow widening the accepted parameters.

Proposal

This RFC proposes to allow ommiting the type entirely in a subclass, as dropping all parameter constraints is always valid according to the LSP principle.

Examples

https://3v4l.org/N3FoQ

<?php

class ArrayClass {
  public function foo(array $foo) { /* ... */ }
}

class IterableClass extends ArrayClass {
  // This implementation also accepts Traversable.
  // Variance is already possible in this special case using "iterable".
  public function foo(iterable $foo) { /* ... */ }
}

class EverythingClass extends ArrayClass {
  // This implementation accepts all values.
  // Restrictions may be done via user code in the method body.
  // Variance is currently not allowed, it throws a warning if parent or child miss a type.
  public function foo($foo) { /* ... */ }
}

Output

Warning: Declaration of EverythingClass::foo($foo) should be compatible with ArrayClass::foo(array $foo) in /in/N3FoQ on line 18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment