Php-new an object but not used, what state is it in memory?

Source: Internet
Author: User
Keywords Php
Like this, for example:

class foo {}$foo = new foo();echo 123;...# 后面一直没有使用$foo这个对象,那么它是会被垃圾回收机制自动回收呢还是一直在内存中?

Reply content:

Like this, for example:

class foo {}$foo = new foo();echo 123;...# 后面一直没有使用$foo这个对象,那么它是会被垃圾回收机制自动回收呢还是一直在内存中?

PHP's GC is based on reference counting, so $foo will not be recycled and will remain in memory until the request is over.

Even if it is new, it is not assigned to $foo, and New Foo () is not necessarily a GC, and PHP's GC triggers are conditional.

Reference

PHP has a variable container to store all PHP variables, and then has a separate identifier to count the number of references to the variable, and when the number of references is 0, the variable is destroyed, which is equivalent to memory reclamation.

Logically you should call this a memory leak because you do not show the Go unset ($foo), which causes the reference count to always be 1! But PHP has a mechanism to prevent this kind of memory leaks, so your memory recycling here is done after the script has been executed.

Specific you can systematically look at this estimate will understand a lot of http://php.net/manual/zh/features.gc.php

I'm just reasoning:
It should be said in two steps that the new class should not cause memory operations, but the assignment actually causes memory allocations. So $ A = new class and $ A = 5; there is actually no difference unless explicitly deleted, otherwise it will persist until the end of the process is automatically reclaimed.

Understanding is not deep, roughly speaking.
object is not used after it is generated, it is a struct with a reference number of 1.
The struct reference number is 0 after leaving the scope, and the memory is reclaimed for the next automatic GC.

Should be automatically recycled, just as the declared object is not used, PHP has an automatic recovery mechanism

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.