php.net |  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
Votes:1
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
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:
24 + 17 = ?
Subscribe to this entry?

 
 [2018-01-12 10:53 UTC] vanleeuwen dot jarno at gmail dot com
Description:
------------
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 (https://3v4l.org/oKeSG).

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:
---------------
<?php
trait Feature {
    public function getClass() {
        $func = function (self $instance) {
            print get_class($instance);
        };
        $func($this);
    }
}

class Foo {
    use Feature;
}

class Bar {
    use Feature;
}

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

Expected result:
----------------
FooBar

Actual result:
--------------
Foo
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

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-01-12 11:07 UTC] pmmaga@php.net
-Status: Open +Status: Feedback
 [2018-01-12 11:07 UTC] pmmaga@php.net
Can you confirm that this is a duplicate of https://bugs.php.net/bug.php?id=75079 ?
 [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] pmmaga@php.net
-Status: Open +Status: Duplicate
 [2018-01-12 11:17 UTC] pmmaga@php.net
Thanks for the confirmation.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 16:01:29 2024 UTC