-1
Input:
<?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);
?>


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

Link: http://php.net/manual/en/language.oop5.basic.php

Please reply with enough explanation.Why $assigned is giving that output at last.

  • 5
    Let's start with why you think it *shouldn't* display that, and we can try and help you understand. – iainn Jul 23 '18 at 13:39
  • 1
    because `$assigned` points to different memory block than `$instance,$reference` points to. Cleaning one block does not cleans the other. – Agnius Vasiliauskas Jul 23 '18 at 13:55

2 Answers2

0

Instance isn't the object, merely a pointer to the object, so assigned is independent.

$instance = new SimpleClass();  // instance points to instantiated object
$assigned   =  $instance;       // assigned also points to same object
$reference  =& $instance;       // reference points to instance which points to object

$instance->var = '$assigned will have this value'; // all get set with this

$instance = null; // instance and reference no longer point to the object, assigned still does

If you var_dump() all three straight after $instance->var = '$assigned will have this value';, you'll see every var has the value.

Reference points to instance, which points to the object. Assigned points to the object and is in no way anything to do with instance.

Hope this helps!

delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
0

Maybe documentation will help you to understand references. Check the first example, especially comments.

You can easily understand that $reference and $instance are "bound" together whereas $assigned is not.

Hope this helps.