4

I'm looking for a way to get the instance ID of a given object / resource with PHP, the same way var_dump() does:

var_dump(curl_init()); // resource #1 of type curl
var_dump(curl_init()); // resource #2 of type curl

How can I get the instance count without calling var_dump()? Is it possible?

Alix Axel
  • 151,645
  • 95
  • 393
  • 500

6 Answers6

6

Convert it to an int to get the resource ID:

$resource= curl_init();
var_dump($resource);
var_dump(intval($resource));
leepowers
  • 37,828
  • 23
  • 98
  • 129
4

Before PHP 8.0:

(int) curl_init();

PHP 8.0+:

spl_object_id(curl_init());

Across versions:

$handle = curl_init();
is_object($handle) ? spl_object_id($hadle) : (int) $handle;
// unset($handle);
hakre
  • 193,403
  • 52
  • 435
  • 836
Joscha
  • 4,643
  • 1
  • 27
  • 34
  • because I initially thought you really need to get the exact string "resource(x) of type Y" - but after I read your question again I figured you really only want the integer value without the clutter ;-) – Joscha Dec 05 '09 at 22:34
  • 1
    In php8, curl_init() no longer returns a resource, it returns an instance of CurlHandle – Simon Jul 08 '21 at 13:16
3

This is a very interesting question... I would be interested to see what you would use this for... but here is one way...

$ch = curl_init();
preg_match("#\d+#", (string) $ch, $matches);
$resourceIdOne = end($matches);

$ch2 = curl_init();
preg_match("#\d+#", (string) $ch2, $matches);
$resourceIdTwo = end($matches);

compare: https://stackoverflow.com/a/68303184/367456

hakre
  • 193,403
  • 52
  • 435
  • 836
Chris Gutierrez
  • 4,750
  • 19
  • 18
  • I won't be using this for anything out of the normal, I was thinking in replacing the var_dump() for a more informative / readable function but I suppose it can be used in a clever registry pattern as well. – Alix Axel Dec 05 '09 at 22:28
1

Convert resource to id with sprintf()

$resource = curl_init();
$id = sprintf('%x', $resource);

// mimic var_dump();
$type = get_resource_type($resource);
echo "resource({$id}) of type ({$type})\n";
Jonny
  • 29
  • 1
  • 2
1

In PHP8 many functions return now a class instance instead of a resource:

$resource = curl_init();
$id = PHP_MAJOR_VERSION >= 8 ? spl_object_id(resource) : (int)resource;

or

$id = is_resource($resource) ? (int)resource : spl_object_id(resource); 
Simon
  • 324
  • 1
  • 13
0
function get_resource_id($resource) {
    if (!is_resource($resource))
        return false;

    return array_pop(explode('#', (string)$resource));
}
silkfire
  • 24,585
  • 15
  • 82
  • 105