Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

How it can print values of Previously assigned value of $A?

The object that is identified by $A is referenced by $B. That's why unset($A) cannot garbage collect the object.

If $A is unset and if $B is going to print value of $A then it should print new value of $A?

No, unset breaks the connection between $A and $B. After that, $A = new stdclass creates a new variable (that happens to have the same name).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top