How to get instance ID with PHP

2019-06-28 02:00发布

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?

5条回答
叛逆
2楼-- · 2019-06-28 02:19
function get_resource_id($resource) {
    if (!is_resource($resource))
        return false;

    return array_pop(explode('#', (string)$resource));
}
查看更多
We Are One
3楼-- · 2019-06-28 02:20

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";
查看更多
做自己的国王
4楼-- · 2019-06-28 02:24

Convert it to an int to get the resource ID:

$resource= curl_init();
var_dump($resource);
var_dump(intval($resource));
查看更多
Root(大扎)
5楼-- · 2019-06-28 02:26

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);
?>
查看更多
Ridiculous、
6楼-- · 2019-06-28 02:37
(int) curl_init()
查看更多
登录 后发表回答