1

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) }
2

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.