Search code examples
phpsolid-principlesliskov-substitution-principle

In PHP does specifying an argument type in a subclass method where the parent method accepts any type break LSP?


If my Interface has a method:

doSomething($param);

And my class which implements this interface specifies the argument type like so:

doSomething(int $param) {}

Does this break the LSP?


Solution

  • Yes: it is sound for a function f2 to be a subtype of another function f1 if f2's arguments are contravariant (and its return type covariant) w.r.t to those of f1.

    Consider your example: a client of the upper doSomething (f1) assumes that it may pass any value to the function, but if the actual implementation being called is the lower doSomething (f2), an error may be raised because this implementation only accepts integers.

    You might also find this article about variances in Scala interesting.