|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75809 self type-hint in anonymous function in trait is wrong on successive calls
Submitted: 2018-01-12 10:53 UTC Modified: 2018-01-12 11:17 UTC
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: vanleeuwen dot jarno at gmail dot com Assigned:
Status: Duplicate Package: Class/Object related
PHP Version: 7.0.27 OS: Any
Private report: No CVE-ID: None
 [2018-01-12 10:53 UTC] vanleeuwen dot jarno at gmail dot com
Starting from PHP 7.0, the self type-hint in an anonymous function within a trait refers back to the first class that created/used the anonymous function. The bug occurs in PHP 7.0, 7.1 and 7.2. This was no problem in PHP 5.6 (

In the example below, classes Foo and Bar do not share anything except for the trait. The anonymous function is created within the local scope of a non-static method, so should not be shared among different objects implementing this trait.

Test script:
trait Feature {
    public function getClass() {
        $func = function (self $instance) {
            print get_class($instance);

class Foo {
    use Feature;

class Bar {
    use Feature;

(new Foo)->getClass();
(new Bar)->getClass();

Expected result:

Actual result:
Fatal error: Uncaught TypeError: Argument 1 passed to Bar::{closure}() must be an instance of Foo, instance of Bar given, called in /in/EafpA on line 24 and defined in /in/EafpA:17
Stack trace:
#0 /in/EafpA(24): Bar->{closure}(Object(Bar))
#1 /in/EafpA(54): Bar->execute()
#2 {main}
  thrown in /in/EafpA on line 17


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2018-01-12 11:07 UTC]
-Status: Open +Status: Feedback
 [2018-01-12 11:07 UTC]
Can you confirm that this is a duplicate of ?
 [2018-01-12 11:12 UTC] vanleeuwen dot jarno at gmail dot com
-Status: Feedback +Status: Open
 [2018-01-12 11:12 UTC] vanleeuwen dot jarno at gmail dot com
Yes, I can confirm this is the same bug. Sorry for the duplicate bug report.
 [2018-01-12 11:17 UTC]
-Status: Open +Status: Duplicate
 [2018-01-12 11:17 UTC]
Thanks for the confirmation.
PHP Copyright © 2001-2023 The PHP Group
All rights reserved.
Last updated: Sun Jan 29 16:05:54 2023 UTC