Function spl_object_hash is Deprecated in PHP 8.6

Function spl_object_hash is Deprecated in PHP 8.6

The spl_object_hash function returns a 32 character string which identifies an object. This string is commonly used as an array key, which makes it possible to track objects in a collection. The spl_object_id function provides the same kind of identifier as an integer.

Since PHP 8.6, the spl_object_hash function is deprecated. Consider the following example which uses the hash as an array key:

<?php

$obj1 = new stdClass();
$obj2 = new stdClass();

$seen = [];
$seen[spl_object_hash($obj1)] = 'first';
$seen[spl_object_hash($obj2)] = 'second';
print_r($seen);

Output:

Deprecated: Function spl_object_hash() is deprecated since 8.6, consider using spl_object_id() instead in main.php on line 7
Deprecated: Function spl_object_hash() is deprecated since 8.6, consider using spl_object_id() instead in main.php on line 8
Array
(
    [00000000000000010000000000000000] => first
    [00000000000000020000000000000000] => second
)

The keys show what the hash actually contains. The value 00000000000000010000000000000000 holds the internal object handle 1, written as padded hexadecimal, and that handle is exactly the number which spl_object_id returns. The hash therefore carries no information beyond the identifier, while taking 32 characters as an array key instead of a single integer.

The example can be fixed by using spl_object_id instead:

<?php

$obj1 = new stdClass();
$obj2 = new stdClass();

$seen = [];
$seen[spl_object_id($obj1)] = 'first';
$seen[spl_object_id($obj2)] = 'second';
print_r($seen);

Output:

Array
(
    [1] => first
    [2] => second
)

Both functions behave the same way after an object is destroyed. The handle is released and reused, so a newly created object can receive the identifier of an object which no longer exists.

Leave a Comment

Cancel reply

Your email address will not be published.