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
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
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

Add a Patch

Pull Requests

Add a Pull Request

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-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 15:01:28 2024 UTC