Bug #80487 [Opn->Nab]: PHP returns static when expecting self
| From: | levim@php.net | Date: | Sat, 05 Dec 2020 03:25:40 +0000 |
| Subject: | Bug #80487 [Opn->Nab]: PHP returns static when expecting self | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-230871@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=80487&edit=1
ID: 80487
Updated by: levim@php.net
Reported by: raincomplain at outlook dot com
Summary: PHP returns static when expecting self
-Status: Open
+Status: Not a bug
Type: Bug
Package: Class/Object related
Operating System: Irrelevant
PHP Version: 8.0.0
Block user comment: N
Private report: N
New Comment:
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.
Previous Comments:
------------------------------------------------------------------------
[2020-12-05 03:20:15] raincomplain at outlook dot com
echo $a->get()->name(); is a typo please ignore it
------------------------------------------------------------------------
[2020-12-05 03:15:25] 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
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=80487&edit=1