phpoopshadow-copy

stdClass object and Shadow Copy strange output


I have following stdClass object and its assignment using reference object. But once after unsetting unset($A); still $B outputs the previous values of $A even a New value is assigned to $A's ->foo property. See the trace below.

<?php
$A = new stdclass;
$A->foo = 'AAA';
echo "Ouput $ A:";
echo "<pre>";
print_r($A);

/*
stdClass Object
(
    [foo] => AAA
)
*/

$B = &$A;
unset($A);

$A = new stdclass;
$A->foo = 'aaa';
echo "after unset $ A and again assigning new value. Ouput $ A:";
echo "<pre>";
print_r($A);
/*   prints like
stdClass Object
(
    [foo] => aaa
)
*/

echo "Ouput $ B:";
echo "<pre>";
print_r($B);
/*  prints like 
stdClass Object
(
    [foo] => AAA
)
*/

Edit:

Question is that $B was assigned a reference of $A but after unset of $A

  1. How it can print values of Previously assigned value of $A?
  2. If $A is unset and if $B is going to print value of $A then it should print new value of $A?

As we know in case of Shadow Copy if source object is vanished/destroyed then a reference object cannot point to a location where source object was pointing.


Solution

  • Rather than saying unset($A), set it to NULL. Unset has so many different behaviors in different cases, its manual is worth a look.

    $A=NULL;
    //unset($A);
    

    Fiddle