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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
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

Pull Requests

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-2024 The PHP Group
All rights reserved.
Last updated: Fri Dec 27 04:01:29 2024 UTC