PHP: destructor vs register_shutdown_function

后端 未结 4 1936
不思量自难忘°
不思量自难忘° 2020-12-16 01:19

I have a PHP class that creates a PNG image on the fly and sends it to browser. PHP manual says that I need to make sure that imagedestroy function is called at end

4条回答
  •  鱼传尺愫
    2020-12-16 01:32

    Based on the principle that you should finish what you start, I'd say the destructor is the correct place for the free call.

    The destructor will be called when the object is disposed of, whereas a shutdown function will not be called until script execution finishes. As noted by Wolfie, these won't necessarily happen if you forcibly halt the server or the script, but at that time, the memory allocated by PHP will be freed anyway.

    Also noted by Wolfie, PHP will free up script resources when the script closes, so if you're only instantiating one of these objects, then you probably wouldn't notice a massive difference. However, if you later do end up instantiating these things, or do so in a loop, then you probably don't want to have to worry about a sudden spike in memory usage, so for the sake of future sanity, I return to my original recommendation; put it in the destructor.

提交回复
热议问题