简体   繁体   English

PHP的实例编号系统如何工作

[英]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. 我已经使用PHP很多年了,但有一部分我从未真正了解过,并且最近一直在想。

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. 正如你所看到的,第一个是1,然后第二个是2,但是它循环而不是坚持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)? 我猜测应用第一个实例的变量会被第二个调用中的新实例覆盖(从而破坏它),但为什么第三个调用会在分配之前破坏第二个实例(将实例增量返回到1) ?

Actually the new instance is created first and then assigned to $a , destroying the previous instance. 实际上,首先创建新实例,然后将其分配给$a ,销毁前一个实例。 So in line one the number 1 is used, in line two, number 1 is still "alive" so the number 2 is used. 因此,在第一行中使用数字1,在第二行中,数字1仍然是“活着的”,因此使用数字2。 Then number 1 is destroyed. 然后数字1被销毁。 Then, in line 3, number 1 is free again, so number 1 is used. 然后,在第3行中,数字1再次空闲,因此使用数字1。

After you second call, instance #1 is already destroyed, so 1 is free again. 第二次调用后,实例#1已经被销毁,因此1再次被释放。 $a holds instance #2 at that time. $a当时持有#2实例。 The next instance, created with your third call, will be assigned #1 again. 使用第三个呼叫创建的下一个实例将再次分配#1

The second instance is destructed after your third call. 第三次通话后,第二个实例被破坏。 Now #1 is used and #2 becomes free again. 现在使用#1#2再次免费。 The fourth call will use #2 again. 第四个呼叫将再次使用#2

And so on and so on… 等等等等…

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM