views:

345

answers:

3

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?

+3  A: 

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

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


$ch2 = curl_init();
preg_match("#\d+#", (string) $ch2, $matches);
$resourceIdTwo = end($matches);
?>
Chris Gutierrez
Very good answer. Would +1 but am out of votes for today :)
Pekka
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
+3  A: 
(int) curl_init()
Joscha
Why the need for substr()?
Alix Axel
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
+3  A: 

Convert it to an int to get the resource ID:

$resource= curl_init();
var_dump($resource);
var_dump(intval($resource));
pygorex1
He mentioned without using `var_dump` ;)
Jakub
So simple... Thanks pygorex1!
Alix Axel
This is actually a very good solution. You could also just do (int) $resource
Chris Gutierrez
or, equivalently: `(int)$resource`. But the manual says that technically this conversion is undefined.
newacct
@pygorex1: You don't happen to have a solution for http://stackoverflow.com/questions/2872366/get-instance-id-of-an-object-in-php, don't you? :)
Alix Axel