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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: mlambley at gmail dot com
New email:
PHP Version: OS:

 

 [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: Sun Jun 16 19:01:30 2024 UTC