如何在PHP中销毁类对象?

时间:2021-08-08 19:34:55

I wrote a little class for storing global variables/functions. My question is - is it necessary to destroy the class object after the script has finished? or will PHP destroy that object itself?

我写了一个用于存储全局变量/函数的小类。我的问题是 - 在脚本完成后是否有必要销毁类对象?或者PHP会破坏该对象本身?

Here's my code:

这是我的代码:

$web=new c_web("myWeb");
$web->loadTemplate("/!framework/admin/template.htm");
$web->doStuff();
// script has finished - destroying required here?

In case I need to destroy it, how can I do that?

如果我需要销毁它,我该怎么做?

3 个解决方案

#1


8  

If the script finishes, the memory is released. You're ready as is :)

如果脚本完成,则释放内存。你已经准备好了:)

#2


4  

No, you do not need to destroy any variable yourself (and an object is a variable) : as soon as your PHP script reaches its end, its variables will be freed, and the correspondig memory released.

不,你不需要自己销毁任何变量(并且一个对象是一个变量):一旦你的PHP脚本到达它的末尾,它的变量将被释放,并且相应的内存被释放。

Actually, a variable gets destroyed automatically when the end of its variable's scope is reached -- and, when you reach end of script, it's the end of the scope introduced by that script's execution.

实际上,当变量到达其变量范围的末尾时,变量会自动被破坏 - 当您到达脚本末尾时,它就是该脚本执行引入的范围的结束。


(Answering a comment to another answer)
Of course, when your script is ended because of an error, the same thing happens : the variables are freed, and the memory released.

(回答另一个答案的评论)当然,当你的脚本由于错误而结束时,同样的事情发生了:变量被释放,内存被释放。

#3


4  

As @Nanne sayd, if the script finished the memory is released, however in some circumstances you might whant to unset($web); .

正如@Nanne所说,如果脚本完成内存被释放,但在某些情况下你可能会想要取消设置($ web); 。

#1


8  

If the script finishes, the memory is released. You're ready as is :)

如果脚本完成,则释放内存。你已经准备好了:)

#2


4  

No, you do not need to destroy any variable yourself (and an object is a variable) : as soon as your PHP script reaches its end, its variables will be freed, and the correspondig memory released.

不,你不需要自己销毁任何变量(并且一个对象是一个变量):一旦你的PHP脚本到达它的末尾,它的变量将被释放,并且相应的内存被释放。

Actually, a variable gets destroyed automatically when the end of its variable's scope is reached -- and, when you reach end of script, it's the end of the scope introduced by that script's execution.

实际上,当变量到达其变量范围的末尾时,变量会自动被破坏 - 当您到达脚本末尾时,它就是该脚本执行引入的范围的结束。


(Answering a comment to another answer)
Of course, when your script is ended because of an error, the same thing happens : the variables are freed, and the memory released.

(回答另一个答案的评论)当然,当你的脚本由于错误而结束时,同样的事情发生了:变量被释放,内存被释放。

#3


4  

As @Nanne sayd, if the script finished the memory is released, however in some circumstances you might whant to unset($web); .

正如@Nanne所说,如果脚本完成内存被释放,但在某些情况下你可能会想要取消设置($ web); 。