Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How PHP's instance numbering system works

I have been using PHP for ages, but there is one part that I have never really learnt about, and have been wondering recently.

When I perform the following:

var_dump(new test());
var_dump(new test());
var_dump(new test());
var_dump(new test());

I get:

object(test)[1]
object(test)[1]
object(test)[1]
object(test)[1]

All these objects have the same number. I get that the system is not assigning the instance to a variable, so it is destructed almost immediately. But when I do the following:

var_dump($a = new test());
var_dump($a = new test());
var_dump($a = new test());
var_dump($a = new test());
var_dump($a = new test());
var_dump($a = new test());

I get:

object(test)[1]
object(test)[2]
object(test)[1]
object(test)[2]
object(test)[1]
object(test)[2]

As you can see, the first one comes through as 1, then the second one is 2, but then it loops rather than sticking to 2.

I am guessing that the variable that the first instance is applied to gets overwritten with the new instance in the second call (thus destructing it), but why does the third call destruct the second instance before assigning it (returning the instance incrementor to 1)?

like image 656
topherg Avatar asked Nov 29 '13 14:11

topherg


2 Answers

Actually the new instance is created first and then assigned to $a, destroying the previous instance. So in line one the number 1 is used, in line two, number 1 is still "alive" so the number 2 is used. Then number 1 is destroyed. Then, in line 3, number 1 is free again, so number 1 is used.

like image 167
Lars Ebert Avatar answered Sep 18 '22 01:09

Lars Ebert


After you second call, instance #1 is already destroyed, so 1 is free again. $a holds instance #2 at that time. The next instance, created with your third call, will be assigned #1 again.

The second instance is destructed after your third call. Now #1 is used and #2 becomes free again. The fourth call will use #2 again.

And so on and so on…

like image 27
Koraktor Avatar answered Sep 19 '22 01:09

Koraktor