Get the reference count of an object in PHP?

后端 未结 5 2251
终归单人心
终归单人心 2021-01-01 18:26

I realize the knee-jerk response to this question is that \"you dont.\", but hear me out.

Basically I am running on an active-record system on a SQL, and in order to

5条回答
  •  隐瞒了意图╮
    2021-01-01 19:18

    Sean's debug_zval_dump function looks like it will do the job of telling you the refcount, but really, the refcount doesn't help you in the long run.

    You should consider using a bounded array to act as a cache; something like this:

    getKey();
          // remove it from its old position
          unset($this->objs[$key]);
          // If the cache is full, retire the eldest from the front
          if (count($this->objs) > $this->max_objs) {
             $dead = array_shift($this->objs);
             // commit any pending changes to db/disk
             $dead->flushToStorage();
          }
          // (re-)add this item to the end
          $this->objs[$key] = $obj;
       }
    
       function get($key) {
          if (isset($this->objs[$key])) {
              $obj = $this->objs[$key];
              // promote to most-recently-used
              unset($this->objs[$key]);
              $this->objs[$key] = $obj;
              return $obj;
          }
          // Not cached; go and get it
          $obj = $this->loadFromStorage($key);
          if ($obj) {
              $this->objs[$key] = $obj;
          }
          return $obj;
       }
    }
    

    Here, getKey() returns some unique id for the object that you want to store. This relies on the fact that PHP remembers the order of insertion into its hash tables; each time you add a new element, it is logically appended to the array.

    The get() function makes sure that the objects you access are kept at the end of the array, so the front of the array is going to be least recently used element, and this is the one that we want to dispose of when we decide that space is low; array_shift() does this for us.

    This approach is also known as a most-recently-used, or MRU cache, because it caches the most recently used items. The idea is that you are more likely to access the items that you have accessed most recently, so you keep them around.

    What you get here is the ability to control the maximum number of objects that you keep around, and you don't have to poke around at the php implementation details that are deliberately difficult to access.

提交回复
热议问题