php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #62135 Closure->bindTo plus $this reassign = corruption
Submitted: 2012-05-24 09:25 UTC Modified: 2012-05-24 10:45 UTC
From: Sjon at hortensius dot net Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.4.3 OS: ArchLinux
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: Sjon at hortensius dot net
New email:
PHP Version: OS:

 

 [2012-05-24 09:25 UTC] Sjon at hortensius dot net
Description:
------------
I just found the bindTo method on a Closure, a started to play with it. I found 
out I can get some serieusly strange behaviour by re-assigning $this. Somehow I 
end up with one variable pointing to different objects?

Test script:
---------------
From: http://3v4l.org/bp598#v540

<?php

class A
{
	public $a = 'public';
}

$m = function (){
	$x =& $this;
	$x = new stdClass;
	var_dump($this, $this->a);
};

$a = new A;
$m = $m->bindTo($a);
$m();

Expected result:
----------------
* Cannot re-assign $this OR
* 'stdClass' + Notice OR
* 'A' + 'public

Actual result:
--------------
object(stdClass)#1 (0) {
}
string(6) "public"

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2012-05-24 10:02 UTC] johannes@php.net
-Status: Open +Status: Not a bug
 [2012-05-24 10:02 UTC] johannes@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

With the "can not reassign $this" message we try to prevent mistakes. For performance and architecture reasons we can't prevent all ways one can shoot in one own's foot though. your behavior also isn't closure related:

class A {
  public$a = "public"; 
  function __construct() {
     $x =& $this;
     $x = new stdClass;
     var_dump($this, $this->a);
   } 
}
new A();

will show the same result. The difference between $this and $this->a comes from the fact that $this is some magic variable.
 [2012-05-24 10:45 UTC] Sjon at hortensius dot net
Ah, too bad; I should have tested that. Thanks for your explanation!
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Tue May 06 19:01:28 2025 UTC