I've learn a while ago on StackOverflow that we can get the "instance ID" of any resource, for instance:
var_dump(intval(curl_init())); // int(2)
var_dump(intval(finfo_open())); // int(3)
var_dump(intval(curl_init())); // int(4)
var_dump(intval(finfo_open())); // int(5)
var_dump(intval(curl_init())); // int(6)
I need something similar but applied to classes:
class foo {
public function __construct() {
ob_start();
var_dump($this); // object(foo)#INSTANCE_ID (0) { }
echo preg_replace('~.+#(\d+).+~s', '$1', ob_get_clean());
}
}
$foo = new foo(); // 1
$foo2 = new foo(); // 2
The above works but I was hoping for a faster solution or, at least, one that didn't involve output buffers. Please note that this won't necessarily be used within the constructor or even inside the class itself!
spl_object_hash()
is not what I'm looking for because the two objects produce identical hashes:
var_dump(spl_object_hash($foo)); // 000000005111e639000000003a87b42e
var_dump(spl_object_hash($foo2)); // 000000005111e639000000003a87b42e
Casting to int like resources doesn't seem to work for objects:
Notice: Object of class foo could not be converted to int.
Is there a quick way to grab the same output without using object properties?
Besides var_dump()
, I've discovered by trial and error that debug_zval_dump()
also outputs the object instance, unfortunately it also needs output buffering since it doesn't return the result.
To the down voters: explain your reasons or, if you think this is a basic question, suggest a solution.