简体   繁体   English

php-为变量分配新变量时的异常行为

[英]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(); 我猜想第二个赋值$ins = new A(); would override the previous $ins reference. 将覆盖先前的$ins参考。

I also don't understand the #1 , #2 , neither the (1),(1) in the var_dump output, I would expect at least (0),(0) . 我也不理解var_dump输出中的#1#2(1),(1) ,我至少期望(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 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. PHP引用是一个别名,它允许两个不同的变量写入相同的值。 As of PHP 5, an object variable doesn't contain the object itself as value anymore. 从PHP 5开始,对象变量不再包含对象本身作为值。 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. 当对象通过参数发送,返回或分配给另一个变量时,不同的变量不是别名:它们持有标识符的副本,该副本指向同一对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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