Pergunta

The comments indicate that I have to clarify my point: I'm a developer and consultant working on foreign code here. My current assignment is to help migrating an existing (very large) system from PHP4 to Java. While reviewing the code I stumbled across a piece of code that quite confuses me.

Some class (let's call it TestClass) in the system I'm working on does something like this:

function reload(){
    $newobject = new TestClass();
    $this = $newobject;
}

I gave it a quick try, expecting some inconsistent behavior between accessing members of the object directly or via some getter in case this somehow works. I thought that at worst the external pointers to the existing object and the internal one (aka $this) would target different portions of the heap.
Quick tests seem to indicate that simply nothing happens.

Any idea if this has any (side) effect whatsoever?

Here is my complete test:

<?php

ini_set('display_errors', true);

class TestClass{

    var $var1;

    function TestClass(){
        $this->var1 = 0;
    }

    function getVar1(){
        return $this->var1;
    }

    function setVar1($value){
        $this->var1 = $value;
    }

    function reload(){
        $newobject = new TestClass();
        $this = &$newobject;
    }
}

echo "<h3>Creating TestObject</h3>";

$testObject = new TestClass();

echo "Accessing member directly: " . $testObject->var1 . "<br>";
echo "Accessing member via get: " . $testObject->getVar1() . "<br>";

echo "Setting member directly to 1<br>";

$testObject->var1 = 1;

echo "Accessing member directly: " . $testObject->var1 . "<br>";
echo "Accessing member via get: " . $testObject->getVar1() . "<br>";

echo "<h3>Calling reload</h3>";

$testObject->reload();

echo "Accessing member directly: " . $testObject->var1 . "<br>";
echo "Accessing member via get: " . $testObject->getVar1() . "<br>";
?>

I expected to get 1 and 0 at last two calls if $this now pointed towards the new object while $testObject would still point to the original one, but 1 is returned in both cases. So I need to know whether the reassignment of $this is doing anything but being a bad idea. If not I can dump that part for good. So if anyone knows of any side effects please tell.

PS: I am fully aware that the above code is not using visibility and such. The original system is written in PHP4 so why bother :-|

Foi útil?

Solução

Okay, with the hint of a colleague I got it. If the reload function is changed to

function reload(){
    $newobject = new TestClass();
    $this = $newobject;
}

the object is overwritten with the content of the newly created one. This is due to the copy on write mentioned by "i put on my robe an wizard hat" in the comment above. If used with the forced call-by-reference nothing happens which is good.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top