Skip to content

39: Replace spl_object_hash() and spl_classes()

Inspect object identity and list SPL classes using supported APIs. PHP 8.6 deprecates both older helper functions.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable spl-object-and-extension-introspection.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/39-spl-object-and-extension-introspection/spl-object-and-extension-introspection.php
spl-object-and-extension-introspection.php
<?php
declare(strict_types=1);
$first = new stdClass();
$alias = $first;
$second = new stdClass();
echo 'Alias shares ID: ', spl_object_id($first) === spl_object_id($alias) ? 'yes' : 'no', PHP_EOL;
echo 'Second shares ID: ', spl_object_id($first) === spl_object_id($second) ? 'yes' : 'no', PHP_EOL;
$classes = new ReflectionExtension('SPL')->getClassNames();
echo 'ArrayObject is in SPL: ', in_array(ArrayObject::class, $classes, true) ? 'yes' : 'no', PHP_EOL;
Alias shares ID: yes
Second shares ID: no
ArrayObject is in SPL: yes

spl_object_id() returns an integer unique among live objects in the process. IDs may be reused once objects are destroyed. If you need an object-keyed map, WeakMap can tie entry lifetime to the key. For extension discovery, reflection returns a list of class names, while spl_classes() returned names as keys as well.

Allocate another stdClass with the same properties and verify that its ID differs while both objects are alive.

Continue with Pass Arrays to Array and Compression APIs.