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
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:
43 - 21 = ?
Subscribe to this entry?

 
 [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-2022 The PHP Group
All rights reserved.
Last updated: Wed Jan 26 23:03:47 2022 UTC