Search code examples
phpinstanceinstances

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)?


Solution

  • 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.