In PHP4 "$this->one = $one;" assigns a *copy* of $one to $this->one. You need to use "$this->one =& $one;"

The code will work as expected in PHP5 (and zend.ze1_compatibility_mode set to off).

Ryan Briones wrote:
This is a scaled down example of something I'm doing in some code. The
results are very funky. I guess I could understand this happening if
$two was out of scope when print_r($this) was called in
One()...actually no I couldn't.

<?php
Class One {
function One() {
$this->test = array();
$two = new Two( $this );
print_r( $this );
}
function set( $index, $value ) {
$this->test[$index] = $value;
}
}


Class Two {
    var $one = null;
    function Two( &$one ) {
        $this->one = $one;
        $this->one->set( 'foo', 1 );
        print_r($this);
    }
}

$obj = new One;
?>

OUTPUT:
two Object
(
    [one] => one Object
        (
            [test] => Array
                (
                    [foo] => 1
                )

        )

)
one Object
(
    [test] => Array
        (
        )

)

This only happens if you assign the reference passed to the second
class as an instance variable. If you call the reference directly, the
variable persists. ie:

<?php
Class One {
function One() {
$this->test = array();
$two = new Two( $this );
print_r( $this );
}
function set( $index, $value ) {
$this->test[$index] = $value;
}
}


Class Two {
    var $one = null;
    function Two( &$one ) {
        $one->set( 'foo', 1 );
    }
}

$obj = new One;
?>

OUTPUT:
one Object
(
    [test] => Array
        (
            [foo] => 1
        )

)

Any Ideas?

Ryan Briones


-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php



Reply via email to