php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #41117 Altering $this via reference weirdness
Submitted: 2007-04-17 12:28 UTC Modified: 2007-05-02 13:27 UTC
Votes:6
Avg. Score:3.7 ± 0.7
Reproduced:5 of 6 (83.3%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: hannes dot magnusson at gmail dot com Assigned: dmitry (profile)
Status: Wont fix Package: Scripting Engine problem
PHP Version: 5CVS-2007-04-17 (CVS) OS: FreeBSD
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 you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: hannes dot magnusson at gmail dot com
New email:
PHP Version: OS:

 

 [2007-04-17 12:28 UTC] hannes dot magnusson at gmail dot com
Description:
------------
Using $this as parameter is possible, but when using it (except from printing it out) $this referes to itself

It is also possible to change $this via reference.
The object name seems to get changed - but when using it it works fine.

Reproduce code:
---------------
<?php
class foo {
        function __construct($this) {
                printf("ctor \$this parameter is: %s\n", var_export($this, 1));
                self::overwrite($this);

                printf("Returning from self::overwrite \$this is: %s", get_class($this));
                $this->hello();
        }
        function overwrite(&$obj) {
                $obj = new stdclass;
                printf("self::overwrite \$this is: %s\n", get_class($this));
        }
        function hello() {
                printf(" ...lier! \$this is still %s\n", get_class($this));
        }
}
$obj = new foo("Hello world");
var_dump($obj);



Actual result:
--------------
ctor $this parameter is: 'Hello world'
self::overwrite $this is: foo
Returning from self::overwrite $this is: stdClass ...lier! $this is still foo
object(foo)#1 (0) {
}


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-04-17 16:35 UTC] judas dot iscariote at gmail dot com
AFAICS, $this should not be altered(reasigned) in anyway.
this should "Fatal error : cannot reassign $this" I guess.
 [2007-05-02 13:27 UTC] dmitry@php.net
The part of the bug that allows use $this as argument name is fixed in CVS HEAD ans PHP_5_2.

However reassignment $this by reference is still possible and won't be fixed (at least in php 5.2).

You can use easest code to do this

$obj =& $this;
$obj = new stdClass();

Both statements are legal, but their combination makes illegal assignment that cannot be detected.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Feb 05 20:01:30 2025 UTC