php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #78807 Method signature types strictly enforced - should allow subclasses
Submitted: 2019-11-13 03:31 UTC Modified: 2019-11-13 04:16 UTC
From: mlambley at gmail dot com Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 7.3.11 OS: All
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
27 - 6 = ?
Subscribe to this entry?

 
 [2019-11-13 03:31 UTC] mlambley at gmail dot com
Description:
------------
Not sure if this is a bug or a feature request, but the example code I have posted produces a warning:
Warning:  Declaration of SubA::fn(SubB $b) should be compatible with A::fn(B $b)

SubB is a subclass of B, so the method override in class SubA should be valid. I would expect the behaviour to be similar to how instanceof works: 
var_dump((new SubB()) instanceof B); //true
That line of code returns true, and it should, because of OOP.

I understand that warnings are not errors, but when I'm publishing modules which may be used by the general public it is impractical to tell them that they must disable warnings.

Is it possible for PHP to respect subclasses in typed method signatures, or will this have unforeseen behaviours I haven't anticipated?

Thank you.

Test script:
---------------
<?php
class A {
    public function fn(B $b) {}
}

class SubA extends A {
    public function fn(SubB $b) {
        parent::fn($b);
    }
}

class B {}
class SubB extends B {}

$obj = new SubA();
$obj->fn(new SubB());


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2019-11-13 04:16 UTC] requinix@php.net
-Status: Open +Status: Not a bug -Package: PHP Language Specification +Package: *General Issues
 [2019-11-13 04:16 UTC] requinix@php.net
https://en.wikipedia.org/wiki/Liskov_substitution_principle
https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)

If A::fn accepts any class of type B, then SubA::fn must also accept any class of type B. That is called contravariance.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 01:01:28 2024 UTC