5

Following is an example in manual:

<?php

    $instance = new SimpleClass();
    $assigned   =  $instance;
    $reference  =& $instance;

    $instance->var = '$assigned will have this value';
    $instance = null; // $instance and $reference become null

    var_dump($instance);
    var_dump($reference);
    var_dump($assigned);
 ?>

I cannot understand the result :

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

Anyone can tell me the answer, I think the three var point the same instance.

Ritesh Kumar Gupta
  • 5,055
  • 7
  • 45
  • 71
tinybai
  • 916
  • 1
  • 6
  • 17

1 Answers1

3
$instance = new SimpleClass(); // create instance
$assigned   =  $instance; // assign *identifier* to $assigned
$reference  =& $instance; // assign *reference* to $reference 

$instance->var = '$assigned will have this value';
$instance = null; // change $instance to null (as well as any variables that reference same)

Assigning via reference and identifier are different. From the manual:

One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples.

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP5, 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.

Check out this answer for more info.

Community
  • 1
  • 1
webbiedave
  • 48,414
  • 8
  • 88
  • 101
  • But i think that the $assigned hold an identifier point to the $instance , then the $instance is assigned null – tinybai Apr 02 '13 at 15:53
  • No, it holds an identifier `to the object pointed to by $instance`, not to `$instance`. – webbiedave Apr 02 '13 at 15:57
  • oh, I know.. It means that $assigned holds an identifier point to the object, while the $instance is null, the object not change? – tinybai Apr 02 '13 at 16:01
  • `$instance = NULL` overwrites the identifier in `$instance` but `$assigned` still holds its identifier. The object is still intact. – webbiedave Apr 02 '13 at 16:03