class a {}for ($i=0; $i < 3; $i++) { $a = new a; var_dump($a); echo "
";}
Output Result:
Object (a) #1 (0) {}
Object (a) #2 (0) {}
Object (a) #1 (0) {}
I want to ask why is #1,#2,#1?
Reply content:
class a {}for ($i=0; $i < 3; $i++) { $a = new a; var_dump($a); echo "
";}
Output Result:
Object (a) #1 (0) {}
Object (a) #2 (0) {}
Object (a) #1 (0) {}
I want to ask why is #1,#2,#1?
The first time new a
, a new object is created.
The second run new a
, and a new object.
And then re-assigned $a
, the first object is useless, it is recycled.
Then the recovered pit is left to the third run to new a
produce the object.
You can experiment with it, and unset
then it's the same.
class a {}for ($i=0; $i < 3; $i++) { $a = new a; var_dump($a); echo "
"; unset($a);}
In-depth, you can find information on GC (garbage collection).
#1
The meaning of the number in is the instance ID (instance ID), which is the corresponding number after the class is instantiated, also known as the object number.
- PHP Automatic garbage collection, using the "reference count" way to determine whether to destroy the variables, the official website has a very detailed explanation.
- Your problem is not with the object, but in how to
$a
count it, the first loop, the variable $ A count is 1, point to the # # object, and the second loop is out of the scope of the first round $ A (elite Prince · 3 hours ago: "The second cycle is out of the scope of the first round $ A" is incorrect, PHP inside loop is not created new scope, destroy the first $a is because it is re-assigned value. ), so I went through the creation of the object # #, destroyed the first created $ A, created a second $ A, assigned the object # $ A, emptied the object # # Several steps, unfortunately I was unable to understand the level of the subtle relationship between them. But it's worth noting that when the object # # was created, the first number of loops was not yet destroyed, otherwise he would have numbered # #.
Because it is mainly the scope of variables, the problem of counting, so unset
similar to the way to help understand:
Give variables a different name and not allow them to count and destroy before the end of the loop
for ($i =0; $i < 3; $i + +) {
$name = ' n '. $i;
${$name} = new StdClass ();
Var_dump (${name});
}
Very respectful of your research spirit, but personally think this knowledge of the use of the scene in PHP is not too much, understanding is good, there is no need to delve into, install xdebug
plug-ins, with xdebug_debug_zval('a')
can be detailed to see the count of variables, or with the IDE in the loop in the next breakpoint, a circle to see the variable value.