php-src icon indicating copy to clipboard operation
php-src copied to clipboard

`spl_object_id` should never reuse an old value

Open mvorisek opened this issue 4 years ago • 6 comments

Description

spl_object_id is often used as a key to store/cache some data related to a specific object instance.

Current behaviour

Currently the returned value can be resused for another object when the original object was released from memory. When the returned value can be resused, it does not provide huge benefit for the user.

Improved behaviour

This is a feature request to update spl_object_id to return always a new/unique value. When the returned value is always guaranteed to be never reused per php instance lifetime, user can rely on this fact without having to further compare the object instance equality (which requires storing the original object reference or some additional value).

x86 version should maintain this new behaviour until all positive integers are used/returned, then reusing of released values can be allowed (preferably with some way to check the exhaustion from user code)

x64 version positive integers space is enough to never overflow in php instance lifetime (would take 292 years to exhaust when every 1ns would be created 1 object [1])

[1] https://www.google.com/search?q=%3D(2^63%2F10^9)%2F(360024365)

mvorisek avatar Dec 31 '21 12:12 mvorisek

This is basically a duplicate of https://bugs.php.net/52657, which has been closed as WONTFIX. Can you give a use-case where you need a unique ID, which cannot be solved by existing means?

cmb69 avatar Dec 31 '21 14:12 cmb69

simple example:

class Data {
    public function getData(object $obj) {
        return $this->data[spl_object_id($obj)];
    }
}

Currently, lookup by spl_object_id() must be combined with another condition to check if the data are really for the given object ID (returned by spl_object_id()) which requeries:

a) the original object stored b) or some extra unique ID stored in the given object

mvorisek avatar Dec 31 '21 16:12 mvorisek

@mvorisek That's precisely what WeakMap is for, which has the additional benefit of releasing unused associated data.

iluuu1994 avatar Dec 31 '21 17:12 iluuu1994

Yes. My point is, what is the advantage of reusing the returned value when it can be unique?

mvorisek avatar Dec 31 '21 17:12 mvorisek

As is, spl_object_id() returns the handle of the object, i.e. the numeric offset into the object store. If we used a unique ID instead, the object store would need to be a hash table instead of a simple array.

But maybe the more relevant question is, why would you need a unique value, if you can already accomplish your use case with a WeakMap?

cmb69 avatar Dec 31 '21 17:12 cmb69

Declining for reasons articulated above.

nikic avatar Jan 01 '22 09:01 nikic