Re: Dissappearing instance variables; Bug or Feature?

From: Date: Sat, 18 Sep 2004 15:12:19 +0000
Subject: Re: Dissappearing instance variables; Bug or Feature?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-197110@lists.php.net to get a copy of this message
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


« previous php.general (#197110) next »