简体   繁体   中英

php - Unexpected behavior when assigning a variable with new

I am a bit confused with the following code example. I would guess that the second assignment $ins = new A(); would override the previous $ins reference.

I also don't understand the #1 , #2 , neither the (1),(1) in the var_dump output, I would expect at least (0),(0) .

Thanks in advance

class A{

    public $var = 2;

}

$ins = new A();

$aux = &$ins;

$ins->var = 3;

var_dump($aux);
echo '<br>';

$ins = new A();

$ins->var = 5;

var_dump($aux);

prints

object(A)#1 (1) { ["var"]=> int(3) }
object(A)#2 (1) { ["var"]=> int(5) }

http://www.php.net//manual/en/language.oop5.references.php

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM