php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #80487 PHP returns static when expecting self
Submitted: 2020-12-05 03:15 UTC Modified: 2020-12-05 03:25 UTC
From: raincomplain at outlook dot com Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 8.0.0 OS: Irrelevant
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: raincomplain at outlook dot com
New email:
PHP Version: OS:

 

 [2020-12-05 03:15 UTC] raincomplain at outlook dot com
Description:
------------
PHP 8 throws a TypeError when expecting static but getting self, which makes sense, but it seems to work the other way around! and PHP will not complain when expecting self but getting static, this is not consistent and can lead to unexpected result too.



Test script:
---------------
class A {
    
    public static function get(): self {
        return new static;
    }
    
    public static function name(): void {
        echo 'A';
    }
}

class B extends A {

    public static function name(): void {
        echo 'B';
    }
}

B::get()::name();
echo $a->get()->name();

Expected result:
----------------
Fatal error: Uncaught TypeError: A::get(): Return value must be of type A, B returned

Actual result:
--------------
B

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-12-05 03:20 UTC] raincomplain at outlook dot com
echo $a->get()->name(); is a typo please ignore it
 [2020-12-05 03:25 UTC] levim@php.net
-Status: Open +Status: Not a bug
 [2020-12-05 03:25 UTC] levim@php.net
There isn't a bug here. A return type of `self` in this case means `A` or any sub-type of `A`. To change this would be a _massive_ backwards compatibility break.
 
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Sat Nov 27 15:03:28 2021 UTC