How long does an instance variable persist? In Rails? In Java? In PHP?

后端 未结 3 1038
礼貌的吻别
礼貌的吻别 2021-01-16 00:49

If I instantiate a class and set an instance variable in a Ruby module used by a Rails controller or model, how long does that instance variable persist? Does a variable nee

相关标签:
3条回答
  • 2021-01-16 01:25

    It exists just within its scope. If it's a global, it will exist for as long as the session does. But if it's not a global, it won't exist after you've left the scope where it exists.

    0 讨论(0)
  • 2021-01-16 01:27

    In Ruby on Rails, it always depends on the scope and where it's defined.

    For example, objects/instance variables defined in your environment and configuration files, will persist always. A simple example of this is ActiveMerchant payment gateways, which are defined in the environment.rb file and are present for every request.

    In case of controllers, it present for that HTTP request alone, the object and the instance variables.

    0 讨论(0)
  • 2021-01-16 01:29

    In PHP, it depends on what version. Considering PHP4 was out a while ago, I'll only talk about 5.2 and 5.3: And yes, variables do need to be stored in a session or some other persistent mechanism (memcached, database, file, etc) to persist across requests. And the longest a native PHP variable can last is the length of the current request (and the end of which everything is cleaned up).

    In Both Versions of PHP:

    Instance variables persist as long as there are variables referencing them. PHP internally stores a reference count on each object. When an variable goes out of scope, PHP decrements the refcount and checks for 0. If it's 0, it cleans up the instance and destroys the object.

    In PHP 5.0, 5.1 and 5.2:

    The variable cleanup is naieve. That means that if you have a circular reference (Class A holds an instance of Class B, and vise versa), the object will never be cleaned up unless one of those references is released.

    In PHP 5.3:

    PHP introduced a rather intelligent garbage collector for the exact reason of circular references. It can be turned off, or manually activated. It runs whenever its root count is full or a refcount is decreased to a non-zero number.

    0 讨论(0)
提交回复
热议问题