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 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: 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-2024 The PHP Group
All rights reserved.
Last updated: Wed Apr 24 18:01:28 2024 UTC